jquery 响应式轮播图
时间: 2023-07-23 22:09:42 浏览: 47
以下是一个基于 jQuery 的简单响应式轮播图的示例代码:
HTML:
```html
<div class="slider">
<div class="slides">
<div class="slide"><img src="img/slide1.jpg"></div>
<div class="slide"><img src="img/slide2.jpg"></div>
<div class="slide"><img src="img/slide3.jpg"></div>
</div>
<div class="controls">
<div class="prev"><i class="fa fa-chevron-left"></i></div>
<div class="next"><i class="fa fa-chevron-right"></i></div>
</div>
</div>
```
CSS:
```css
.slider {
position: relative;
width: 100%;
max-width: 1200px;
margin: 0 auto;
}
.slides {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch;
}
.slide {
scroll-snap-align: start;
flex-shrink: 0;
width: 100%;
height: 500px;
}
.slide img {
width: 100%;
height: 100%;
object-fit: cover;
}
.controls {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
display: flex;
justify-content: space-between;
z-index: 1;
}
.prev, .next {
cursor: pointer;
padding: 20px;
background-color: rgba(255, 255, 255, 0.8);
border-radius: 50%;
transition: background-color 0.5s;
}
.prev:hover, .next:hover {
background-color: rgba(255, 255, 255, 1);
}
.prev {
margin-left: 20px;
}
.next {
margin-right: 20px;
}
```
JavaScript:
```js
$(function() {
var slider = $(".slider"),
slides = slider.find(".slides"),
slide = slides.find(".slide"),
prevBtn = slider.find(".prev"),
nextBtn = slider.find(".next"),
slideCount = slide.length,
slideWidth = 100.0 / slideCount,
slideIndex = 0;
slide.each(function(index) {
$(this).css({"left": (slideWidth * index) + "%"});
});
function showSlide(index) {
slides.stop().animate({"left": (-100 * index) + "%"}, 500);
slide.eq(index).addClass("active").siblings().removeClass("active");
}
function nextSlide() {
slideIndex++;
if (slideIndex == slideCount) {
slideIndex = 0;
}
showSlide(slideIndex);
}
function prevSlide() {
slideIndex--;
if (slideIndex < 0) {
slideIndex = slideCount - 1;
}
showSlide(slideIndex);
}
prevBtn.on("click", prevSlide);
nextBtn.on("click", nextSlide);
$(window).resize(function() {
slideWidth = 100.0 / slideCount;
slide.each(function(index) {
$(this).css({"left": (slideWidth * index) + "%"});
});
showSlide(slideIndex);
});
});
```
这个轮播图会自动适应浏览器窗口大小,并且可以在移动设备上进行触摸滑动。你可以根据需要修改 CSS 样式和 JavaScript 代码来实现自己想要的效果。