我已成功将图像从左向右移动。但是当我试图从右向左移动图像时,图像也向右移动。实际上x的值不减小.x = x-step不会减小x的值。将不胜感激。
<script>
function disp(){
var step=1; // Change this step value
var y=document.getElementById('i1').offsetTop;
var x=document.getElementById('i1').offsetLeft;
if(x <= 550 && y<=500 && y>=0 && x>=0)
{
x=x-step;
document.getElementById('i1').style.left= x + "px"; // horizontal movment
}
}
function timer(){
disp();
var y=document.getElementById('i1').offsetTop;
var x=document.getElementById('i1').offsetLeft;
my_time=setTimeout('timer()',100);
}
</script>
<img src=image2.jpg id='i1' style="height:20px;width:20px;position:relative;left:300px;top:300px;">
答案 0 :(得分:0)
将您的步数更改为10,您将看到它向左移动2px,将步长设置为6,您将看到它向右移动2px。这是因为8px的offsetleft和left之间存在差异,导致了有趣的行为
你可以像这样减去差异:var x = document.getElementById(&#39; i1&#39;)。offsetLeft - 8; (或计算差异),翻转x = x-step;到x = x +步;它会向相反的方向移动
<html>
<meta charset="utf-8" />
<img src='image2.jpg' id='i1' style="height:20px;width:20px;position:relative;left:300px;top:300px;" />
<script>
function disp(){
var step=1; // Change this step value
var y=document.getElementById('i1').offsetTop;
var x=x=document.getElementById('i1').offsetLeft - 8;
if(x <= 550 && y <=500 && y>=0 && x>=0)
{
x=x-step;
document.getElementById('i1').style.left = x + "px";
}
}
function timer(){
disp();
var y=document.getElementById('i1').offsetTop;
var x=document.getElementById('i1').offsetLeft;
my_time=setTimeout('timer()',100);
}
timer();
</script>
</html>
答案 1 :(得分:0)
请查看this fiddle
function disp(){
var step;
var y=document.getElementById('i1').offsetTop;
var x=document.getElementById('i1').offsetLeft;
if (x>1000){
clearTimeout(my_time);
}
if (x>=400){
dir = "left";
} else if (x<0){
dir = "right";
}
if(dir == "left")
{
step = -10;
} else {
step = 10;
}
x = x + step;
document.getElementById('i1').style.left= x + "px"; // horizontal movment
}
function tmr(){
disp();
my_time=setTimeout(function(){ tmr(); } ,100);
}
var my_time;
var dir = "right";
tmr();