原生JS轮播图
2021-04-19 19:26
标签:for 20px row llb callback 代码 fir 默认 bsp 还有自己封装的动画函数 原生JS轮播图 标签:for 20px row llb callback 代码 fir 默认 bsp 原文地址:https://www.cnblogs.com/royal6/p/12267306.htmlHTML代码
div class="focus">
a href="javascript:void(0);" class="arrow-l"> < a>
a href="javascript:void(0);" class="arrow-r"> > a>
ul>
li>img src="upload/focus.png">li>
li>img src="upload/focus1.jpg">li>
li>img src="upload/focus2.jpg">li>
li>img src="upload/focus3.jpg">li>
ul>
ol class="circle">ol>
div>
css代码
*{
margin: 0;
padding: 0;
}
ol{list-style: none;}
a{text-decoration: none;}
.focus{
position: relative;
float: left;
width: 721px;
height: 455px;
background-color: blue;
overflow: hidden;
}
.focus ul {
position: absolute;
top: 0;
left: 0;
width: 600%;
}
.focus ul li {
float: left;
}
.arrow-l,
.arrow-r {
display: none;
position: absolute;
top: 50%;
margin-top: -20px;
width: 24px;
height: 40px;
background: rgba(0, 0, 0, .3);
text-align: center;
line-height: 40px;
color: #fff;
font-size: 18px;
z-index: 2;
}
.arrow-r {
right: 0;
}
.circle {
position: absolute;
bottom: 10px;
left: 50px;
}
.circle li {
float: left;
width: 8px;
height: 8px;
/*background-color: #fff;*/
border: 2px solid rgba(255, 255, 255, 0.5);
margin: 0 3px;
border-radius: 50%;
/*鼠标经过显示小手*/
cursor: pointer;
}
.current {
background-color: #fff;
}
JavaScript代码
window.addEventListener(‘load‘,function(){
//1.获取元素
var arrow_l = document.querySelector(‘.arrow-l‘);
var arrow_r = document.querySelector(‘.arrow-r‘);
var focus = document.querySelector(‘.focus‘);
//2.鼠标经过显示左右按钮
focus.addEventListener(‘mouseenter‘,function(){
arrow_l.style.display = ‘block‘;
arrow_r.style.display = ‘block‘;
//停止定时器,并清空
clearInterval(timer);
timer = null;
});
focus.addEventListener(‘mouseleave‘,function(){
arrow_l.style.display = ‘none‘;
arrow_r.style.display = ‘none‘;
timer = setInterval(function(){
//手动调用点击事件
arrow_r.click();
},2000);
});
//3.动态生成圆圈
var ul = focus.querySelector(‘ul‘);
var ol = focus.querySelector(‘ol‘);
for(var i=0; i
function animate(obj, target, callback) {
// 先清除以前的定时器,只保留当前的一个定时器执行
clearInterval(obj.timer);
obj.timer = setInterval(function() {
// 步长值写到定时器的里面
var step = (target - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetLeft == target) {
// 停止动画 本质是停止定时器
clearInterval(obj.timer);
// 回调函数写到定时器结束里面
callback && callback();
}
// 把每次加1 这个步长值改为一个慢慢变小的值 步长:(目标值 - 现在的位置) / 10
obj.style.left = obj.offsetLeft + step + ‘px‘;
}, 15);
}