繁体   English   中英

为什么不单击按钮就调用函数?

[英]Why is function being called without clicking on button?

我正在尝试在html中移动按钮的较小块“ onclick”。 但是,要么没有调用该函数,要么甚至在单击按钮之前就在调用它。 如何找出并解决以获得所需的响应?

<html>
<head>
<script>
var pos = 0;
//getting box element
var box = document.getElementById("box");
var time = setInterval(move, 10);
document.getElementById("btn1").onclick = move(){
    if(pos >= 150){
        clearInterval(time);
    } else{
        pos += 1;
        box.style.left = pos+"px";
    }
};
</script>
</head>
<body>
<h1><p id="p1" style="color:#dd3333">Sample Game</p></h1>
<p id="p2" styel="color:#b5b5b5">Click on the button below</p>
<style>
#container{
width:200px;
height:200px;
background:green;
position:relative;
}
#box{
width:50px;
height:50px;
background:red;
position:absolute;
}
</style>
<div id="container">
<div id="box"></div>
</div>
<br></br>
<button id="btn1">Click Me</button>
</body>

</html>

您直接调用函数move 代替:

function move(){
    if(pos >= 150){
        clearInterval(time);
    } else{
        pos += 1;
        box.style.left = pos+"px";
    }
}


document.getElementById("btn1").addEventListener("click", move);

另外,由于您不使用任何DOM就绪处理程序来确保文档已准备就绪并已被JS解析,因此请将<script>文件放在结束</body>标记之前。 或快速谷歌搜索如何结合这样的功能,它将告诉您JS可以安全地对DOM元素进行操作。 (例如,这里的jQuery是您的朋友)

 <!DOCTYPE html> <html> <head> </head> <body> <style> #container { width: 200px; height: 200px; background: green; position: relative; } #box { width: 50px; height: 50px; background: red; position: absolute; } </style> <div id="container"> <div id="box"></div> </div> <button id="btn1">Click Me</button> <script> var pos = 0; var box = document.getElementById("box"); var time = null; function move() { if (pos >= 150) { clearInterval(time); } else { pos += 1; box.style.left = pos + "px"; } } document.getElementById("btn1").addEventListener("click", function() { time = setInterval(move, 10); }); </script> </body> </html> 

如果您不需要重用该功能,请尝试此操作。

   document.getElementById('btn1').onclick = function()
   {
       alert('you clicked me');
   }
<html>
<head>

</head>
<body>
<h1><p id="p1" style="color:#dd3333">Sample Game</p></h1>
<p id="p2" styel="color:#b5b5b5">Click on the button below</p>
<style>
#container{
width:200px;
height:200px;
background:green;
position:relative;
}
#box{
width:50px;
height:50px;
background:red;
position:absolute;
}
</style>
<div id="container">
<div id="box"></div>
</div>
<br></br>
<button id="btn1">Click Me</button>
<script>

function move(){
if(pos >= 150){
    clearInterval(time);
} else{
    pos += 1;
    box.style.left = pos+"px";
}
}


document.getElementById("btn1").addEventListener("click", move);
var pos = 0;
//getting box element
var box = document.getElementById("box");
var time = setInterval(move, 10);
</script>
</body>

</html>

暂无
暂无

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

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