简体   繁体   中英

How do you place an image and make it move using Javascript?

CSS:

#sharks {
    content:url(sharks.jpg);
    position:absolute;
}

JS:

var winHeight = window.innerHeight;// get the window height & width
var winWidth = window.innerWidth;
var clock;
var index = 0;

function do_move(image) {
    fish = document.getElementById(image);
    horz = fish.style.left;
    horz = parseInt(horz.substring(0,horz.length-2));
    fish.style.left = (horz+1)+'px';
}

function add_shark() {

    var height = Math.floor((Math.random()*winHeight)+100);
    var image = document.createElement("IMG");
    image.setAttribute("id", "sharks" + index);
    image.setAttribute("style", "position:absolute;top:"+height+"px;left:0px;");
    document.body.appendChild(image);
    do_move(image.id);
    index++;
}

HTML:

<input type="button" value="Add a Shark" onclick="add_shark();">

Looking at this code, I am hoping the use the button in the HTML to place an image of a shark on one side of the screen that will simply move to the other side.

Currently, this code places a shark on the screen on the left side, at a random Y point, but it doesn't move.

Any help would be greatly appreciated.

What you need to do is to use window.setTimeout() to have your move function call itself over and over to make the animation happen.

This could should be close to what you want, but I haven't actually run it yet:

function do_move(image) {
    fish = document.getElementById(image);
    horz = fish.style.left;
    horz = parseInt(horz.substring(0,horz.length-2));

    // How far we are moving the image each "step"
    horz += 10;
    fish.style.left = (horz)+'px';

    // The total distance we are moving the image
    if (horz < 500) {
      // Set things up to call again
      window.setTimeout(function() {
        do_move(image);
      }, 250);  // 1/4 of a second
    }
}

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