One of Multiple Tasks Operated by Button Won't Execute

谁说我不能喝 提交于 2020-01-06 05:34:30

问题


I'm having problems with one of multiple tasks being executed by a button. The button executes two of three tasks (hides them upon .(click)), except the last one, a text-blinking javascript function. I can't see what can be possibly wrong! The same syntax to hide the text before it is the same syntax used to hide the next one, but for some reason it won't hide it (the blinking text). Thanks in advance for your help!

Here is my code:

<!DOCTYPE html>
<html>
<head>
<style>
body {
    background-color: coral;
    color: white;
}

.text1{
 padding-left: 15px;
 color: white; 
 font-family: 'Orbitron', sans-serif;
 width: 250px;
 float: left;
 padding-top: 10px;
}


.text2{
  color: white;
  width: 100px;
  float: right;
  padding-top: 10px;
}


</style>
<link rel="stylesheet" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".btn1").on('click',function(){
      $("p").hide();
      $(".text1").hide();
      $(".text2").hide();
      $('body').css("background", "black");  

    });

    var element = $(".text2");
    var shown = true;
    setInterval(toggle, 500);

    function toggle() {
     if(shown) {
        element.hide();
     } else {
        element.show();
     }
    shown = !shown;
  }


});
</script>

</head>
<body>
  <div class="text1">
  PRESS BUTTONS BELOW
  </div>
  <div class="text2">-- : --</div>  
  <button class="btn1">online</button>
</body>
</html>

回答1:


To hide .text2 clear the setInterval using clearInterval

$(document).ready(function() {
  $(".btn1").on('click', function() {
    $("p").hide();
    $(".text1").hide();
    $(".text2").hide(function() {
      clearInterval(x)
    });
    $('body').css("background", "black");

  });

  var element = $(".text2");
  var shown = true;
  var x = setInterval(toggle, 500);

  function toggle() {
    if (shown) {
      element.hide();
    } else {
      element.show();
    }
    shown = !shown;
  }


});
body {
  background-color: coral;
  color: white;
}

.text1 {
  padding-left: 15px;
  color: white;
  font-family: 'Orbitron', sans-serif;
  width: 250px;
  float: left;
  padding-top: 10px;
}

.text2 {
  color: white;
  width: 100px;
  float: right;
  padding-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text1">
  PRESS BUTTONS BELOW
</div>
<div class="text2">-- : --</div>
<button class="btn1">online</button>


来源:https://stackoverflow.com/questions/48971674/one-of-multiple-tasks-operated-by-button-wont-execute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!