作者:sunsijia | 来源:互联网 | 2022-08-22 23:49
本文实例为大家分享了Javascript实现简单的轮播图的具体代码,供大家参考,具体内容如下
js轮播图实现思路
1、先获取元素 盒子 左右按钮
2、鼠标经过 显示/隐藏 左右侧按钮
3、动态生成小圆圈、 添加自定义属性
4、小圆圈点击事件 添加current类名
5、添加动画事件 animate 等于 -索引号*focusWidth
6、克隆第一张图片到最后面
7、添加右侧/左侧按钮点击事件
8、设置定时器 手动调用右侧按钮点击事件
html代码部分
css样式部分
* {
padding: 0;
margin: 0;
}
li {
list-style: none;
}
img {
border: 0;
vertical-align: top;
}
a {
text-decoration: none;
}
.focus {
position: relative;
width: 721px;
height: 455px;
margin: 100px auto;
overflow: hidden;
}
.focus ul {
position: absolute;
top: 0;
left: 0;
width: 600%;
}
.focus ul li {
float: left;
}
.arrow_r,
.arrow_l {
display: none;
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
font-size: 24px;
background: rgba(0, 0, 0, .2);
color: #fff;
z-index: 1;
}
.arrow_r {
right: 0;
}
.circle {
position: absolute;
bottom: 10px;
left: 50px;
}
.circle li {
float: left;
width: 8px;
height: 8px;
border: 2px solid rgba(255, 255, 255, .5);
border-radius: 50%;
margin: 0 3px;
cursor: pointer;
}
.current {
background-color: #fff;
}
Javascript部分
window.addEventListener('load', function() {
//获取元素
var focus = document.querySelector('.focus');
var arrow_r = document.querySelector('.arrow_r');
var arrow_l = document.querySelector('.arrow_l');
var focusWidth = focus.offsetWidth;
// 鼠标经过focus盒子 显示/隐藏 左右侧按钮 暂停轮播
focus.addEventListener('mouseenter', function() {
arrow_r.style.display = 'block';
arrow_l.style.display = 'block';
clearInterval(timer);
timer = null;
});
focus.addEventListener('mouseleave', function() {
arrow_r.style.display = 'none';
arrow_l.style.display = 'none';
timer = setInterval(function() {
//调用点击事件
arrow_r.click();
}, 2000);
});
//动态生成小圆圈
var ul = focus.querySelector('ul');
var ol = focus.querySelector('.circle');
for (var i = 0; i
0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetLeft == target) {
clearInterval(obj.timer);
callback && callback();
}
obj.style.left = obj.offsetLeft + step + 'px';
}, 15);
}
//自动轮播放轮播图
var timer = setInterval(function() {
//调用点击事件
arrow_r.click();
}, 2000);
});
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。