<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
list-style: none;
}
.box {
width: 450px;
height: 300px;
margin: 50px auto;
position: relative;
}
.pic {
width: 450px;
height: 300px;
border: 1px solid #000;
position: relative;
overflow: hidden;
}
.pic ul {
width: 2250px;
height: 300px;
position: absolute;
}
.pic ul li {
width: 450px;
height: 300px;
background: red;
font-size: 30px;
line-height: 300px;
text-align: center;
float: left;
}
.num {
position: absolute;
right: 5px;
bottom: 5px;
}
.num ul li {
width: 20px;
height: 20px;
font-size: 16px;
line-height: 20px;
text-align: center;
float: left;
border: 1px solid #000;
background: yellow;
margin: 0 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box">
<div class="pic">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<div class="num">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
</div>
<button>anni</button>
<div class='box1' style="width: 100px;height: 100px;background: red;position: absolute;"></div>
<script type="text/javascript">
var pic = document.getElementsByClassName("pic")[0];
var num = document.getElementsByClassName("num")[0];
var box1 = document.getElementsByClassName("box1")[0];
var ulone = pic.getElementsByTagName("ul")[0];
var btn = document.getElementsByTagName("button")[0];
// console.log(ulone)
var listtwo = num.getElementsByTagName("li");
var timer = null;
for(var i = 0 ; i < listtwo.length ; i++){
listtwo[i].index = i;//将索引值赋值
listtwo[i].onclick = function(){
var list = this.index;//定义索引值
animation(-list*450,ulone);//注意往左移动的时候是负值,往右移动是正值
}
}
function animation(target,ele){
// 使用定时器之前,要先清除定时器
clearInterval(timer);
// 定义速度
var speed = target > ele.offsetLeft ? 10 : -10;
timer = setInterval(function(){
// 求出目标位置和当前位置的差值,如果差值小于步速,不足一步的时候,直接将盒子运动到目标位置,要放到定时器内,因为每运动一次都要计算一次
var val = target - ele.offsetLeft;
ele.style.left = ele.offsetLeft + speed + "px";
if(Math.abs(val) <= Math.abs(speed)){
ele.style.left = target + "px";
clearInterval(timer);
}
},10);
};
</script>
</body>
</html>
javascript动画之焦点图
最新推荐文章于 2023-03-06 14:43:36 发布