标签:doc bottom 属性 round view computed += tom init
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>简单的运动</title> <style> div{ width: 50px; height: 50px; background: #CC66CC; margin-bottom: 20px; position: relative; } </style> </head> <body> <!-- 两个div使用一个运动函数,一个向右移动350px,一个向右移动590px,每次移动3px --> <input type="button" value="开始运动"> <div id="div1"></div> <div id="div2"></div> <script> window.onload = function(){ var btn = document.querySelector("input"); var div1 = document.querySelector("#div1"); var div2 = document.querySelector("#div2"); var timer; function move(obj,attr,target){ clearInterval(obj.timer); obj.timer = setInterval(function(){ var val = parseInt(getComputedStyle(obj)[attr]); val +=3; if(val>=target){ clearInterval(obj.timer); val = target; } obj.style[attr] = val+"px"; },16); } btn.onclick = function(){ move(div1,"left",350); move(div2,"left",590); } } </script> </body> </html>
1.在使用定时器时,要根据情况先清除其他定时器,避免多次点击属性值变化加快。
2.修订最后运动停止的值,注意运动目标值与改变值(代码中target、val)之间的关系。
标签:doc bottom 属性 round view computed += tom init
原文地址:https://www.cnblogs.com/amy2017/p/9788718.html