[英]How to make an image move by clicking on a button with Javascript?
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. 我需要在具有以下行为的HTML文档中编写JavaScript代码:单击按钮时,图像开始移动(如果尚未移动),每秒向左移动一个像素。 When a second button is clicked, the image stops moving and immediately gets repositioned to its original coordinates. 单击第二个按钮时,图像停止移动,并立即重新定位到其原始坐标。
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. 现在,如果我单击图像,则图像每秒向左移动1个像素。 However I need to carry that function over to the button called START. 但是,我需要将该功能传递给名为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>
change cat
to button1
将cat
更改为button1
document.getElementById('button1').onclick=function(){
//--^^^^^^^^----here
if(timerid == null){
timerid = setInterval("move()", 10);
}else{
clearInterval(timerid);
timerid = null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.