window.setTimeout条件下的问题

时间:2018-11-29 11:09:29

标签: javascript jquery html css

我正在一个网站上工作,该网站的加载页面持续5秒钟,您可以在其中选择是否要激活自动播放。即使执行条件,由于某些原因,自动播放仍会运行。这是代码,希望有人可以提供帮助。

body .loading {
  text-align: center;
}

body #content {
  display: none;
}
<!doctype html>
<html lang=en>

<head>
  <meta charset="UTF-8">
  <title>Home</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>

<body>

  <div class="loading">
    <input type="button" value="Click Here to mute" class="autoplay" id="autoplayno" />
  </div>

  <div id="content">
    <iframe class="embed-responsive-item" id="iframesc" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/users/334742776&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true&start_track=1"
      allow="autoplay"></iframe>
  </div>

</body>

<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<!--Loading Page-->
<script>
  $(".loading").fadeOut(5000, function() {
    $("#content").fadeIn(2000);
  });
</script>

<!--The script which is not working-->
<script>
  var hasBeenClicked = false;
  $("#autoplayno").click(function() {
    hasBeenClicked = true;
  });

  if (hasBeenClicked) {
    $("#iframesc").attr("src", "https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/users/334742776&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true&start_track=1");
    $("#autoplayno").attr("value", "Sound mutted");
  } else {
    window.setTimeout(function() {
      $("#iframesc").attr("src", "https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/users/334742776&color=%23ff5500&auto_play=true&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true&start_track=1")
    }, 4000)
  }
</script>


</html>

1 个答案:

答案 0 :(得分:1)

Read的开头为hasBeenClicked

false条件为iffalse分支已运行。

在将来的某个时候,可能有人会单击自动播放按钮并将else更改为hasBeenClicked……但是您再也不会看它了,并且您已经选择了要使用的URL。

可能您想将 entire true节放在传递给if的函数中,而不是将setTimeout分支的内容放在{{ 1}}。