js无缝轮播没有左右按钮,移入小圆点改变图片
时间: 2023-08-18 12:10:10 浏览: 146
实现 JS 无缝轮播,鼠标移入小圆点改变图片的方法有很多,以下是其中一种实现方式:
HTML 代码:
```html
<div id="slider">
<ul id="slider-list">
<li><img src="img/1.jpg" alt="图片1"></li>
<li><img src="img/2.jpg" alt="图片2"></li>
<li><img src="img/3.jpg" alt="图片3"></li>
<li><img src="img/4.jpg" alt="图片4"></li>
<li><img src="img/5.jpg" alt="图片5"></li>
</ul>
<ul id="slider-dots">
<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
```
CSS 代码:
```css
#slider {
position: relative;
width: 600px;
height: 400px;
overflow: hidden;
}
#slider-list {
position: absolute;
width: 3000px;
height: 400px;
padding: 0;
margin: 0;
list-style: none;
transition: left 0.5s ease;
}
#slider-list li {
float: left;
width: 600px;
height: 400px;
}
#slider-dots {
position: absolute;
right: 20px;
bottom: 20px;
padding: 0;
margin: 0;
list-style: none;
}
#slider-dots li {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 10px;
border-radius: 50%;
background-color: #ccc;
cursor: pointer;
}
#slider-dots li.active {
background-color: #f00;
}
```
JS 代码:
```javascript
window.onload = function() {
var sliderList = document.getElementById("slider-list");
var sliderItems = sliderList.getElementsByTagName("li");
var sliderDots = document.getElementById("slider-dots");
var sliderDotItems = sliderDots.getElementsByTagName("li");
var sliderIndex = 0;
var maxIndex = sliderItems.length / 2 - 1;
var animateInterval;
// 复制列表项,实现无缝轮播
sliderList.innerHTML += sliderList.innerHTML;
// 自动轮播
animateInterval = setInterval(function() {
sliderIndex++;
if (sliderIndex > maxIndex) {
sliderList.style.left = "0px";
sliderIndex = 1;
}
sliderList.style.left = -(sliderIndex * 600) + "px";
setActiveDot();
}, 2000);
// 鼠标移入小圆点切换图片
for (var i = 0; i < sliderDotItems.length; i++) {
sliderDotItems[i].index = i;
sliderDotItems[i].onmouseover = function() {
sliderIndex = this.index;
sliderList.style.left = -(sliderIndex * 600) + "px";
setActiveDot();
};
}
// 设置当前小圆点状态
function setActiveDot() {
for (var i = 0; i < sliderDotItems.length; i++) {
sliderDotItems[i].className = "";
}
sliderDotItems[sliderIndex % 5].className = "active";
}
};
```
这段代码实现了一个横向方向的无缝轮播,每隔两秒钟切换一张图片。鼠标移入小圆点切换图片。可以根据实际需要进行修改。
阅读全文