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


看这段代码,我希望使用HTML中的按钮将鲨鱼图像放置在屏幕的一侧,然后将其移动到另一侧。

当前,此代码在屏幕的左侧随机向Y点放置了一个鲨鱼,但它没有移动。

任何帮助将不胜感激。

最佳答案

您需要执行的操作是使用window.setTimeout()反复调用自身的move函数以使动画发生。

这应该接近您想要的,但是我还没有真正运行它:

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

关于javascript - 如何放置图片并使用Javascript移动图片?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19825613/

10-11 05:08
查看更多