DIV CSS 佈局教程網

JavaScript 簡單實現點擊左右運動的方法
編輯:關於JavaScript     

本文分享一個點擊控制方塊左右移動的效果:點擊「向右」方塊右移,點擊「向左」方塊左移。

可以用 setInterval 每隔一段時間讓 div 移動固定距離來實現運動。要點一:若元素左側距離小於目標距離則正向移動,否則反向移動。

 if(run.offsetLeft <target){ speed = 2; }else{ speed = -2; }

要點二:若元素左側距離等於目標距離就停止計時器,否則讓左側距離等於當前距離加上速度值。

 if(run.offsetLeft ==target){ clearInterval(timer); } else{ run.style.left = run.offsetLeft +speed +"px"; }

程式碼如下:

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>無標題文檔</title> <style> body{margin:0; padding:0;} #run{width:100px; height:100px; background:#06c; position:absolute; border:1px solid #000; left:0;} </style> <script> window.onload = function(){ var run = document.getElementById("run"); var btn = document.getElementById("btn"); var btn1 = document.getElementById("btn1"); var speed = 2; var timer = null; btn.onclick = function(){ startrun(300); } btn1.onclick = function(){ startrun(0); } function startrun(target){ clearInterval(timer); timer = setInterval(function(){ if(run.offsetLeft <target){ speed = 2; }else{ speed = -2; } if(run.offsetLeft ==target){ clearInterval(timer); } else{ run.style.left = run.offsetLeft +speed +"px"; } },30) } } </script> </head> <body> <input id="btn" type="button" value="運動向右"> <input id="btn1" type="button" value="運動向左"> <div id="run"></div> </body> </html>

希望本文所述對大家的 JavaScript 程式設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved