写一个js原生轮播图,只需要实现图片自动无限循环播放,且切换时有动画
时间: 2024-03-24 22:39:00 浏览: 65
好的,我可以为您提供一个简单的js原生轮播图代码示例,代码如下:
HTML结构:
```html
<div class="slider">
<ul class="slider-list">
<li class="slider-item"><img src="image1.jpg"></li>
<li class="slider-item"><img src="image2.jpg"></li>
<li class="slider-item"><img src="image3.jpg"></li>
</ul>
</div>
```
CSS样式:
```css
.slider {
width: 500px;
height: 300px;
position: relative;
overflow: hidden;
}
.slider-list {
width: 1500px; /* 图片总宽度 */
position: absolute;
left: 0;
top: 0;
}
.slider-item {
float: left;
width: 500px;
height: 300px;
}
```
JS代码:
```js
// 获取轮播图元素
var slider = document.querySelector('.slider');
var sliderList = slider.querySelector('.slider-list');
var sliderItems = slider.querySelectorAll('.slider-item');
// 克隆首尾两张图片
var firstItem = sliderItems[0].cloneNode(true);
var lastItem = sliderItems[sliderItems.length - 1].cloneNode(true);
sliderList.insertBefore(lastItem, sliderItems[0]);
sliderList.appendChild(firstItem);
// 计算轮播图总宽度和每张图片的宽度
var totalWidth = sliderItems.length * slider.offsetWidth;
sliderList.style.width = totalWidth + 'px';
var itemWidth = slider.offsetWidth;
// 设置轮播图初始位置
var currentIndex = 1;
var offset = -currentIndex * itemWidth;
sliderList.style.transform = 'translateX(' + offset + 'px)';
// 图片轮播动画
function slide() {
currentIndex++;
var offset = -currentIndex * itemWidth;
sliderList.style.transition = 'transform 0.5s ease-in-out';
sliderList.style.transform = 'translateX(' + offset + 'px)';
}
sliderList.addEventListener('transitionend', function () {
if (currentIndex >= sliderItems.length - 1) {
currentIndex = 1;
sliderList.style.transition = 'none';
var offset = -currentIndex * itemWidth;
sliderList.style.transform = 'translateX(' + offset + 'px)';
}
if (currentIndex <= 0) {
currentIndex = sliderItems.length - 2;
sliderList.style.transition = 'none';
var offset = -currentIndex * itemWidth;
sliderList.style.transform = 'translateX(' + offset + 'px)';
}
});
// 5秒自动轮播
var timer = setInterval(slide, 5000);
// 鼠标移入停止轮播,移出继续轮播
slider.addEventListener('mouseenter', function () {
clearInterval(timer);
});
slider.addEventListener('mouseleave', function () {
timer = setInterval(slide, 5000);
});
```
这段代码实现了轮播图的图片自动无限循环播放,并且切换时有动画效果,您可以根据自己的需求进行修改。
阅读全文