<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>移动案例</title>
<style>
.box{
width: 100px;
height: 100px;
background-color: green;
position: absolute;
top: 100px;
}
</style>
</head>
<body>
<input type="button" value="移动到400px" id="btn1">
<input type="button" value="移动到800px" id="btn2">
<br>
<div class="box" id="dv"></div>
<script>
function $(id) {
return document.getElementById(id)
}
//运动框架
function animate(ele,target,step) {
let s = step //把当前的步数进行记录
//先清理定时器
clearInterval(ele.timer)
ele.timer = setInterval(function () { //ele是一个对象,把定时器的变量变为一个对象的属性
//获取当前的div的位置
var current = ele.offsetLeft;
//div移动的步数
//判断是从左或从右走
step = current<target?s:-s;//当前的距离小于目标值时,需要为正的步数,否则为负数
//每次移动后的距离
current+= step;
//判断当前移动后的位置是否到达目标位置
if(Math.abs(target-current)>Math.abs(step)){ //当为负数时,有绝对值比较数字
ele.style.left = current+'px';//当大于步数时,说明还有距离
}else{
clearInterval(ele.timer)
ele.style.left = target+'px'; //当小于步数时,说明当时已经接近目标,就直接让他到目标位置
}
},20)
}
$('btn1').onclick = function () {
animate($('dv'),400,10)
};
$('btn2').onclick = function () {
animate($('dv'),800,10)
}
function Move(left,step,ele) {
var current = ele.offsetLeft; //获取当前的位置
current +=step;
if(current<=left){
ele.style.left = current+'px';
}else{
return;
}
}
//匀速前进,最终移到400px,
// var timer = null; //只产生一个定时器
// $('btn1').onclick = function () {
// setInterval(function() {
// Move(400,10,$('dv'))
// }, 20)
//
// //setInterval(Move(400,10),20)
// }
// $('btn2').onclick = function () {
// setInterval(function () {
// Move(800,10,$('dv'))
// },20)
// }
</script>
</body>
</html>
运动模块1
猜你喜欢
转载自blog.csdn.net/weixin_42355871/article/details/84838197
今日推荐
周排行