2017-08-23 40 views
0

我只是在一个JavaScript课程的中间,我正在玩一个非常基础的项目,我需要随机出现随机形状(只是正方形和圆形)在页面上的位置。一旦开始按钮被点击,第一个形状需要在随机延迟后出现。setTimeOut导致函数触发按钮被点击前

本来我是在画布上绘制形状,但是随后绘制的形状需要稍后才能点击,因为我只需要生成正方形和圆形,我只使用形状各异的div,大小和位置。点击按钮后,我的形状显得很好,但我正努力在功能上添加延迟。这是我的代码,而无需延迟:

<button id="start">Start</button> 
    <div id="shape"></div> 

    <script type="text/javascript"> 

    function generateRandomShape() { 
     var randomColor = ["red", "green", "blue", "orange", "purple"]; 
     var radiusOptions = ["50%", ""] 
     document.getElementById("shape").style.backgroundColor = randomColor[Math.floor(Math.random() * randomColor.length)]; 
     document.getElementById("shape").style.borderRadius = radiusOptions[Math.floor(Math.random() * radiusOptions.length)]; 
     document.getElementById("shape").style.height = Math.random() * 500; 
     document.getElementById("shape").style.width = document.getElementById("shape").style.height; 
     document.getElementById("shape").style.marginLeft = Math.random() * 1000; 
     document.getElementById("shape").style.marginTop = Math.random() * 400; 
    }; 

    document.getElementById("start").onclick = generateRandomShape; 

    </script> 

我试图修改的onclick电话如下:

 document.getElementById("start").onclick = setTimeOut(generateRandomShape,2000); 

但现在没有被点击的按钮后2秒的函数触发(我将加入在随机元素延时使用Math.random一旦我得到这个工作!)。无法理解为什么这是在事件处理程序之前触发的逻辑。

回答

1

这条线:

document.getElementById("start").onclick = setTimeOut(generateRandomShape,2000); 

导致setTimout功能,因为一旦它遇到,执行功能和返回值(如果有的话)是什么被分配到onclick财产立即运行。

行更改为:

document.getElementById("start").onclick = function(){setTimeout(generateRandomShape,2000)}; 

,使得包含setTimeout指令的功能被存储在onclick财产,不会运行,直到click事件发生。此外,您的大写错误setTimeoutsetTimeOut

此外,您的script标签中不需要type=text/javascript

除此之外,你的函数没有写得很好。您应该只扫描元素一个时间,而不是在你的代码的每一行,像这样:

function generateRandomShape() { 
 

 
    var randomColor = ["red", "green", "blue", "orange", "purple"]; 
 
    var radiusOptions = ["50%", ""] 
 
    var shape = document.getElementById("shape"); // <-- Just scan for the element once 
 
    
 
    shape.style.backgroundColor = randomColor[Math.floor(Math.random() * randomColor.length)]; 
 
    shape.style.borderRadius = radiusOptions[Math.floor(Math.random() * radiusOptions.length)]; 
 
    shape.style.height = Math.random() * 500; 
 
    shape.style.width = shape.style.height; 
 
    shape.style.marginLeft = Math.random() * 1000; 
 
    shape.style.marginTop = Math.random() * 400; 
 
}; 
 

 
// It's better to use modern standards for event wiring (.addEventListener) 
 
// instead of event properties (.onclick) 
 
document.getElementById("start").addEventListener("click",function(){ 
 
    // You had mis-capitalized setTimeout as setTimeOut! 
 
    setTimeout(generateRandomShape,2000) 
 
});
<button id="start">Start</button> 
 
<div id="shape">This is the shape element.</div>

+0

真棒这是真正有用的和超清晰。非常感谢你的帮助! – DaveB1