繁体   English   中英

Javascript使用屏幕上的按钮向左或向右移动图像

[英]Javascript Moving an Image Left or Right Using Onscreen Buttons

好的,我一直在网上寻找构建平台的方法,并且我正在逐步进行。 我已经有了所需的图像,以及如何在屏幕上放置它们。 我也知道如何做一个积分系统,但是我还远远没有完成。 现在,我想知道如何使用屏幕上的按钮从左向右移动播放器。 我正在寻找的东西与我在这里找到的这段代码完全不同,因为它看起来太多了,它只是将字符向右移动而不停。

我在寻找:

1)左右两个按钮

2)按下按钮可在左右方向上移动播放器。

3)释放按钮时,播放器停止移动。

// Other code
...
    imgObj.style.left = '0px'; 
}
function moveRight() {
    imgObj.style.left = parseInt(imgObj.style.left) + 1 + 'px';
}
function stop() {
    clearTimeout(animate);
    imgObj.style.left = '0px'; 
}
window.onload =init;
//-->
</script>
</head>
<body>
    <form>
        <img id="myImage" src="/images/html.gif" />
        <p>Click the buttons below to handle animation</p>
        <input type="button" value="Start" onclick="moveRight();" />
        <input type="button" value="Stop" onclick="stop();" />
    </form>
</body>
</html>

干得好。 希望它对您来说不是太多的代码:)

JSfiddle演示在这里

<head>
<style>
    #sprite { position:relative; } // needed for the img to be free to move around
</style>
<script>
    var timer_id; // reference of the timer, needed to stop it
    var speed = 50; // pixels/second
    var period = 40; // milliseconds
    var sprite; // the element that will move
    var sprite_speed = 0; // move per period
    var sprite_position = 100; // pixels


    function animate ()
    {
        sprite_position += sprite_speed;
        if (sprite_position < 0) sprite_position = 0;
        if (sprite_position > 200) sprite_position = 200;
        sprite.style.left = sprite_position+'px';
    }

    function move(direction)
    {
        if (timer_id) stop();
        sprite_speed = speed * period/1000 * direction;
        timer_id = setInterval (animate, period);
    }

    function stop()
    {
        clearInterval (timer_id);
        timer_id = null;
    }

    function init()
    {
       sprite = document.getElementById ("sprite"); // the HTML element we will move
       animate(); // just to initialize sprite position
    }

    window.onload =init; // start doing things once the page has loaded
</script>
</head>
<body>
    <img id="sprite" src="http://petiteleve.free.fr/SO/yoshi.png" />
    <p>Click the buttons below to handle animation</p>
    <input type="button" value="Left"  onmousedown="move(-1);" onmouseup="stop();"/>
    <input type="button" value="Right" onmousedown="move( 1);" onmouseup="stop();"/>
</body>

这仅仅是概念的证明。
与发布Mario Bross 25相比,您还有很长的路要走,但这是朝正确方向迈出的一步。
还是离开了?

暂无
暂无

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

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