扫码关注官方订阅号
为什么不足取整后还会出现这种现象?
无标题文档
欢迎选择我的课程,让我们一起见证您的进步~~
你是通过 i 来控制左右移动的。另外可能你对setInterval的理解有点偏差,如果你没有清除这个定时器,他将会一直执行,也就是说,你首次点击后第一个定时器会启动,而且一直执行下去,再点击一次,第二个也会启动,一个是对left进行加,一个进行减,所以导致抖动。修改后的代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> #p1{width:100px;height:100px;background:red;position:absolute;} </style> <script> window.onload = function() { var op = document.getElementById('p1'); var oBtn= document.getElementById('btn'); oBtn.onclick = move; }; var i=0; var timer = null function move() { clearInterval(timer); i++; if(i%2==1){ timer = setInterval(function() { var op = document.getElementById('p1'); var speed = (80-op.offsetLeft)/8; speed = speed > 0?Math.ceil(speed) : Math.floor(speed); if (speed == 0) {clearInterval(timer);}; op.style.left = op.offsetLeft + speed + 'px'; },30)} else{ timer=setInterval(function() { var op = document.getElementById('p1'); var speed = (0-op.offsetLeft)/8; speed = speed > 0?Math.ceil(speed) : Math.floor(speed); if (speed == 0) {clearInterval(timer);}; op.style.left = op.offsetLeft + speed + 'px'; document.title=op.offsetLeft+','+speed; },30) } } </script> </head> <body> <input type="button" value="move" id="btn"/> <p id="p1"></p> </body> </html>
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
你是通过 i 来控制左右移动的。另外可能你对setInterval的理解有点偏差,如果你没有清除这个定时器,他将会一直执行,也就是说,你首次点击后第一个定时器会启动,而且一直执行下去,再点击一次,第二个也会启动,一个是对left进行加,一个进行减,所以导致抖动。修改后的代码如下: