简体   繁体   中英

Moving an image from right to left by using style.left

I have moved the image left to right successfully. But when I tried to move image from right to left then also image moves towards right.actually the value of x in not decreasing.x=x-step doesn't decreases value of x. Help will be appreciated.

<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;">

Change your step to 10 and you will see it move left by 2px, set the step to 6 and you will see it move right by 2px. this is becuase there is a difference between the offsetleft and left by 8px, causing the funny behavior

You can subtract the diff like so: var x=document.getElementById('i1').offsetLeft - 8; (or calculate the difference), flip the x=x-step; to x=x+step; and it will move the opposite direction

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

Check out this fiddle please

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM