手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >js简单实现点击左右运动的方法
js简单实现点击左右运动的方法
摘要:本文实例讲述了js简单实现点击左右运动的方法。分享给大家供大家参考。具体分析如下:这里可实现点击向右,方块向右移动,点击向左,方块向左移动的...

本文实例讲述了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程序设计有所帮助。

【js简单实现点击左右运动的方法】相关文章:

jQuery仿gmail实现fixed布局的方法

js比较日期大小的方法

js实现鼠标划过给div加透明度的方法

javascript实现可全选、反选及删除表格的方法

js实现div层缓慢收缩与展开的方法

javascript实现Table间隔色以及选择高亮的方法

js去字符串前后空格的实现方法

js实现鼠标经过表格行变色的方法

jQuery实现表格行上移下移和置顶的方法

JavaScript实现点击文字切换登录窗口的方法

精品推荐
分类导航