如何通过单击带有 Javascript 的按钮使图像移动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15698973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:45:54  来源:igfitidea点击:

How to make an image move by clicking on a button with Javascript?

javascripthtmlfunctiontimermove

提问by tidydee

I need to write a javascript code inside an HTML document that has the following behavior: When a button is clicked, an image starts moving (if it is not already moving), one pixel to the left per second. When a second button is clicked, the image stops moving and immediately gets repositioned to its original coordinates.

我需要在具有以下行为的 HTML 文档中编写 javascript 代码:单击按钮时,图像开始移动(如果它尚未移动),每秒向左移动一个像素。当单击第二个按钮时,图像停止移动并立即重新定位到其原始坐标。

I get everything to work, except for the "Button" that says "START". Right now if I click the image the image moves left 1 pixel per second. However I need to carry that function over to the button called START.

除了显示“开始”的“按钮”之外,我让一切正常工作。现在,如果我单击图像,图像会以每秒 1 个像素的速度向左移动。但是,我需要将该功能传递给名为 START 的按钮。

Does anyone know how to do this? Thank you!!

有谁知道如何做到这一点?谢谢!!

My code is as follow:

我的代码如下:

<html><head>


<script>

var timerid = null;


function move()
{
document.getElementById('cat').style.right = 
    parseInt(document.getElementById('cat').style.right) + 1 + 'px';    
}

window.onload=function()
{   



document.getElementById('cat').onclick=function(){

    if(timerid == null){
        timerid = setInterval("move()", 10);
    }else{
        clearInterval(timerid);
        timerid = null;
    }
}   


var button2 = document.getElementById('button2');
button2.onclick= reloadPage;

    function reloadPage(){
        window.location.reload();
    }

}


</script>
</head>
<body>

<img id="cat" src="cat.jpg" style="position:absolute;right:5px"/>

<div>
<button id="button1" type="button" style="position:absolute;left:10px;top:190px"/>START</button>
<button id="button2" type="button" style="position:absolute;left:10px;top:220px"/>STOP & RESET</button>
</div>

</body>
</html>

回答by bipen

change catto button1

更改catbutton1

document.getElementById('button1').onclick=function(){
                     //--^^^^^^^^----here
  if(timerid == null){
    timerid = setInterval("move()", 10);
  }else{
    clearInterval(timerid);
    timerid = null;
  }
}