繁体   English   中英

如何放置图片并使用Javascript移动图片?

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

看这段代码,我希望使用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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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