首先先写好基本的框架
接下用CSS设定好大致样式
{
margin: 0;
padding: 0;
}.promo {
position: relative;
width: 846px;
height: 472px;
margin: 100px auto;
background-color: deeppink;
}.promo img {
width: 846px;
height: 473px;
}.prev {
display: none;
position: absolute;
top: 50%;
left: 0px;
margin-top: -15px;
width: 20px;
height: 30px;
background-color: rgb(0, 0, 0, .3);
text-align: center;
line-height: 30px;
text-decoration: none;
border-radius: 0 15px 15px 0;
color: #fff;
}.next {
display: none;
position: absolute;
top: 50%;
right: 0px;
margin-top: -15px;
width: 20px;
height: 30px;
background-color: rgb(0, 0, 0, 0.3);
text-align: center;
line-height: 30px;
text-decoration: none;
border-radius: 15px 0 0 15px;
color: #fff;
}.circle {
position: absolute;
bottom: 10px;
left: 50%;
margin-left: -50px;
width: 100px;
height: 20px;
background-color: rgb(255, 255, 255, .3);
border-radius: 10px;
}.promo ol li {
float: left;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #fff;
margin: 6px;
}.promo ul {
position: absolute;
width: 600%;
}
.promo ul li {
float: left;
}li {
list-style: none;
}.promo .circle .selected {
background-color: #ff5b00;
}
效果如图
接下来开始通过JS实现功能
鼠标经过时显示左右按钮,离开时不显示
promo.addEventListener('mouseenter', function () {
prev.style.display = 'block';
next.style.display = 'block';
clearInterval(timer);
timer = null;
})
promo.addEventListener('mouseleave', function () {
prev.style.display = 'none';
next.style.display = 'none';
timer = setInterval(function () {
next.click()
}, 2000)
})
动态生成小圆圈(数量由选取图片的数量决定)同时点击小圆圈以切换图片
for (var i = 0; i < ul.children.length - 1; i++) {
var li = document.createElement('li')
li.setAttribute('index', i);
ol.appendChild(li);
li.addEventListener('click', function () {
for (var i = 0; i < ol.children.length; i++) {
ol.children[i].className = '';
}
this.className = 'selected';
var index = this.getAttribute('index')
num = index;
circle = index;
animate(ul, -index * promoWidth);
})
}
因为左右按钮点击使小圆圈选定都一样,所以设定一个函数circleChange
function circleChange() {
for (var i = 0; i < ul.children.length - 1; i++) {
ol.children[i].className = '';
}
ol.children[circle].className = 'selected';
}
点击左侧按钮以进行图片的滚动(右侧按钮同理)
prev.addEventListener('click', function () {
if (num == 0) {
num = ul.children.length - 1;
ul.style.left = -num * promoWidth + 'px';
}
num--;
animate(ul, -num * promoWidth, callback);
circle--;
if (circle < 0) {
circle = ol.children.length - 1;
}
circleChange();
});
结束~