js使用定时器实现轮播图效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
img {
vertical-align: top;
width: 960px;
height: 320px;
}
ul {
width: 4800px;
list-style: none;
overflow: hidden;
position: absolute;
left: 0px;
}
li {
float: left;
}
.wrap {
position: relative;
width: 960px;
height: 320px;
border: 1px solid #00498B;
overflow: hidden;
margin: 20px auto;
}
.menu {
position: absolute;
left: 50%;
bottom: 0;
transform: translate(-50%);
}
.menu>span {
cursor: pointer;
display: inline-block;
width: 30px;
height: 30px;
background-color: #0000FF;
font-size: 20px;
text-align: center;
line-height: 30px;
color: #fff;
}
.menu .active {
background: red;
}
</style>
</head>
<body>
<div class="wrap">
<ul>
<li><img src="./images/l-1.jpg" alt="t"></li>
<li><img src="./images/l-2.jpg" alt="t"></li>
<li><img src="./images/l-3.jpg" alt="t"></li>
<li><img src="./images/l-4.jpg" alt="t"></li>
</ul>
<div class="menu">
<span class="active">1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
</div>
</body>
</html>
window.onload = function() {
//获取元素
var ul = document.querySelector('ul');
var liS = document.querySelectorAll('li');
var span = document.querySelectorAll('span');
for (var i = 0; i < span.length; i++) {
span[i].id = i;
span[i].onclick = function() {
//让点击的序号背景色变红
for(var i=0; i<span.length; i++){
span[i].className = '';
}
this.className = 'active';
//切换到对应下标的图片
// ul定位公式:-序号下标*图片宽度
//var left = this.id * (-960);
var left = -this.id * liS[0].clientWidth;
move(ul,'left',20,left);
}
}
//执行任意元素某个方向的移动动画 用法:move(元素,'属性',步长,终点);
// move(ul, 'left', 20, 900);
var timer = null; //定时器id
function move(ele, attr, step, end) {
//清除定时器防止叠加
clearInterval(timer);
//获取起点 处理步长的正负
/*判断正负
正: 当前值 目标值
0 500
负: 当前值 目标值
500 0
*/
step = end > parseInt(getStyle(ele, attr)) ? step : -step;
//定时器
timer = setInterval(function() {
//1.在当前值的基础上 + step
var speed = parseInt(getStyle(ele, attr)) + step;
//3.到达目标点停止
if ((speed >= end && step > 0) || (speed <= end && step < 0)) {
//往前走用的判断 step:正的
speed = end;
clearInterval(timer);
}
//2.移动的是ele的attr
ele.style[attr] = speed + 'px';
}, 20);
}
//获取任意元素的非行内样式 用法:getStyle(元素,'属性');
function getStyle(ele, attr) {
if (ele.currentStyle) { //ie8-
return ele.currentStyle[attr];
} else { //标准浏览器
return getComputedStyle(ele)[attr];
}
}
}
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634786.html