用jqery写一个商品点击的案例,当点击时切换图片,没有点击时图片进行轮播,鼠标放入时图片不轮播,鼠标不放入时图片轮播
时间: 2024-05-15 17:19:58 浏览: 89
使用JQuery实现图片轮播效果的实例(推荐)
HTML代码:
```
<div class="product">
<div class="images">
<img src="image1.jpg" alt="Product Image">
<img src="image2.jpg" alt="Product Image">
<img src="image3.jpg" alt="Product Image">
</div>
<div class="description">
<h2>Product name</h2>
<p>Product description</p>
<button class="buy">Buy Now</button>
</div>
</div>
```
jQuery代码:
```
$(document).ready(function() {
var images = $(".images img");
var currentIndex = 0;
var interval = setInterval(function() {
if (!images.hasClass("active")) {
images.eq(currentIndex).addClass("active");
currentIndex = (currentIndex + 1) % images.length;
images.eq(currentIndex).removeClass("active");
}
}, 3000);
images.click(function() {
clearInterval(interval);
images.removeClass("active");
$(this).addClass("active");
});
$(".product").hover(function() {
clearInterval(interval);
}, function() {
interval = setInterval(function() {
if (!images.hasClass("active")) {
images.eq(currentIndex).addClass("active");
currentIndex = (currentIndex + 1) % images.length;
images.eq(currentIndex).removeClass("active");
}
}, 3000);
});
});
```
CSS代码:
```
.product {
display: flex;
justify-content: space-between;
align-items: center;
width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 5px #ccc;
}
.images {
position: relative;
width: 50%;
height: 300px;
}
.images img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.images img.active {
opacity: 1;
}
.description {
width: 50%;
padding: 0 20px;
text-align: center;
}
.description h2 {
font-size: 24px;
margin: 0 0 10px 0;
}
.description p {
font-size: 16px;
margin: 0 0 20px 0;
}
.buy {
display: block;
width: 100%;
padding: 10px;
background-color: #f39c12;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.5s ease-in-out;
}
.buy:hover {
background-color: #e67e22;
}
```
阅读全文