js简单实现点击左右运动的方法

前端技术 2023/09/08 JavaScript

本文实例讲述了js简单实现点击左右运动的方法。分享给大家供大家参考。具体分析如下:

这里可实现点击向右,方块向右移动,点击向左,方块向左移动的效果

可以用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 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>
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程序设计有所帮助。

本文地址:https://www.stayed.cn/item/21537

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。