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";
}
上代码
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-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:1pxsolid#000;
left:0;}
</style>
<script>
window.onload=function(){
varrun=document.getElementById("run");
varbtn=document.getElementById("btn");
varbtn1=document.getElementById("btn1");
varspeed=2;
vartimer=null;
btn.onclick=function(){
startrun(300);
}
btn1.onclick=function(){
startrun(0);
}
functionstartrun(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>
<inputid="btn"type="button"value="运动向右">
<inputid="btn1"type="button"value="运动向左">
<divid="run"></div>
</body>
</html>
希望本文所述对大家的javascript程序设计有所帮助。