马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 小黄练编程 于 2022-4-16 22:20 编辑 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.topback{
position:fixed;
bottom:50%;
right:0;
background-color:green;
}
.topback .toppback {
position:absolute;
top:0;
left:0;
width:160px;
height:50px;
text-align:left;
line-height:50px;
background-color:green;
z-index:-1;
}
.topback i{
display:inline-block;
width:50px;
height:50px;
text-align:center;
line-height:50px;
background-color:green;
cursor:pointer;
}
</style>
</head>
<body>
<div class="topback">
<span><a href="#"><i></i></a></span>
<div class="toppback"><a href="#">返回顶部</a></div>
</div>
<script src="/js/index.js"></script>
<script>
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);
if(callback){
callback();
}
}
obj.style.left=obj.offsetLeft+step+'px';
},30);
}
var topback=document.querySelector('.topback');
var toppback=document.querySelector('.toppback');
topback.addEventListener('mouseenter',function(){
animate(toppback,-140);
});
</script>
</body>
</html>
offsetLeft 偏移量初始为 0,之后递减为 -140,在递减过程 始终大于你的 target = -140 导致 一直满足 if 条件,进入 if 代码卡后定时器被取消 之后又 回调所以不正常
|