为什么没有点击按钮就调用函数?

时间:2017-03-29 19:05:44

标签: javascript html

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

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

3 个答案:

答案 0 :(得分:2)

您直接调用函数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,例如你的朋友)

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

onclick="window.location.href = 'https://youtube.com'"

答案 2 :(得分:0)

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