簡體   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