简体   繁体   English

javascript,jquery。 不会淡出

[英]javascript, jquery. won't fadeOut

I am new to javascript and jquery, so, as a challenge, I am doing little game and ran into the problem today.我是 javascript 和 jquery 的新手,所以,作为一个挑战,我正在做一个小游戏,今天遇到了这个问题。

So, the code works like: there appears some text and after some time it needs to fadeOut , but it just won't fadeOut for me...所以,代码的工作原理是:出现一些文本,一段时间后它需要fadeOut ,但对我来说它不会fadeOut ......

Here's my code:这是我的代码:

var timeToStart = 3;      
var timer = 0;

function count() {            
    document.getElementById("gameStarter").innerHTML = timeToStart + " s";      
    timeToStart = timeToStart - 1;            
} 

$("#start").click(function() {            
    $("#gameStart").fadeIn(500, function() {        
        timer = setInterval(count, 1000);                
        setTimeout(function() {clearInterval(timer);}, 4000);       
        if (timeToStart == 0) {      
            $("#gameStart").fadeOut(500)            
        }                       
    });
});

(gcampbell and Patrick Evans pointed this out in the comments. As they haven't posted an answer, I'll post a CW.) (gcampbell 和 Patrick Evans 在评论中指出了这一点。由于他们还没有发布答案,我将发布 CW。)

Your code here你的代码在这里

timer = setInterval(count, 1000);

setTimeout(function() {clearInterval(timer);}, 4000);

if (timeToStart == 0) {

  $("#gameStart").fadeOut(500)

}

only runs your if statement once, before everything is finished running.在一切都完成运行之前,只运行一次 if 语句。 Right now it passes over it once, when timeToStart still equals 3. I recommend putting your if statement inside of your count() function like this现在它通过它一次,当 timeToStart 仍然等于 3 时。我建议将你的 if 语句放在你的 count() 函数中,像这样

function count() {

  document.getElementById("gameStarter").innerHTML = timeToStart + " s";

  timeToStart = timeToStart - 1;

  if (timeToStart == 0) {

    $("#gameStart").fadeOut(500)

  }

} }

so it checks it every time its run, instead of only once.所以它每次运行时都会检查它,而不是只检查一次。

Live Example:现场示例:

 $("#gameStart").hide(); var timeToStart = 3; var timer = 0; function count() { document.getElementById("gameStarter").innerHTML = timeToStart + " s"; timeToStart = timeToStart - 1; if (timeToStart == 0) { $("#gameStart").fadeOut(500) } } $("#start").click(function() { $("#gameStart").fadeIn(500, function() { timer = setInterval(count, 1000); setTimeout(function() { clearInterval(timer); }, 4000); }); });
 <div id="gameStarter"></div> <div id="gameStart">This is gamestart</div> <input type="button" id="start" value="Start"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

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

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