- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <title>Document</title>
- <style type="text/CSS">
- * {
- margin: 0;
- padding: 0;
- }
- div {
- position: absolute;
- top: 50px;
- width: 100px;
- height: 100px;
- background-color: red;
- }
- input {
- width: 100px;
- height: 30px;
- color: #fff;
- background-color: yellowgreen;
- }
- </style>
- </head>
- <body>
- <div></div>
- <input type="button" value="移动到200" />
- <input type="button" value="移动到400" />
- <script type="text/javascript">// 封装函数,盒子和目标距离都是不确定的,我们可以将他们作为参数传递。
- function animation(tag,target) {
- var timer = null,
- currentDistance = tag.offsetLeft,
- step = 5;
- step = currentDistance < target? step: -step;// 判断step的正负,200到400时是递增,400到200时是递减
- timer = setInterval(function() {
- if(Math.abs(currentDistance - target) > Math.abs(step)) { // 这里判断条件也要略作改动,使用绝对值进行比较
- currentDistance += step; /
- tag.style.left = currentDistance + 'px';
- }else {
- tag.style.left = target + 'px' // 当当前距离与目标距离之间的差值小于step改变的距离时,我们直接让盒子移动到目标距离。
- clearInterval(timer);
- timer = null;
- }
- },17)
- }
- var btns = document.querySelectorAll('input'),
- dv = document.querySelector('div');
- btns[0].addEventListener('click',function() {
- animation(dv,200);
- })
- btns[1].addEventListener('click',function() {
- animation(dv,400);
- })
- </script>
- </body>
- </html>
来源: