用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>



原文地址:https://www.cnblogs.com/jingangel/p/2390656.html