2.3.2解决目标值
-
问题1:目标值问题
-
分析原因
-
开始飞 if (current >= target)
-
往回飞 if (current <= target)
-
-
解决方法:根据step判断
-
开始飞 step 10 > 0
-
往回飞 step 10 < 0
-
-
<body> <button>开始飞</button> <button>往回飞</button> <br> <img src="./img/right.gif" alt=""> <script> // 1.点击一下 向右移动10px var btn = document.getElementsByTagName("button"); var oImg = document.getElementsByTagName("img")[0]; var timer; // 2.开始飞 btn[0].onclick = function () { // 改变图片路径 oImg.src = "./img/right.gif"; move(oImg, "left", 10, 1000) } // 2.往回飞 btn[1].onclick = function () { // 改变图片的路径 oImg.src = "./img/left.gif"; move(oImg, "left", -10, 0) } /* 问题1:目标值问题 分析原因 开始飞 if (current >= target) 往回飞 if (current <= target) 解决方法 根据step判断 开始飞 step 10 > 0 往回飞 step 10 < 0 */ function move(elem, attr, step, target) { /* elem 移动的元素 attr 改变的属性 step步长 可以是正数也可以是负数 target目标值 */ clearInterval(timer);// timer这里存储的就是定时器id 先把原先的定时器清除掉 timer = setInterval(function () { // 在left值的基础上+10 先获取到left值 var current = parseInt(getStyle(elem, attr)) + step if (step > 0 && current >= target) { current = target; // 停止定时器 clearInterval(timer) } else if (step < 0 && current <= target) { current = target; clearInterval(timer); } elem.style[attr] = current + "px"; }, 50) } </script> </body>