按钮中的自动启动倒数计时器

时间:2018-05-04 09:53:43

标签: javascript html

我正在尝试在我的页面中实施倒数计时器,以显示该页面何时会重定向到google.com。到目前为止,我已经创建了一个按钮,但它只会在我点击它时开始计数。当我访问该页面时,是否可以使按钮自动开始倒计时?

<button id="myButton" class="butstyle" style="float:right">Click To Redirect</button>


<script>

var counter = 10;
$('.butstyle').on('click',function(e){

e.preventDefault();
e.stopPropagation();

if($(this).hasClass('butstyle')){

$('.butstyle').text('You will be redirected in: 10 seconds');
$(this).removeClass().addClass('butAfter');

var int = setInterval(function() {
    counter--;
    $('.butAfter').text('You will be redirected in: '+counter+' seconds');

    if (counter == 0) {

        clearInterval(int);
        counter = 10;
        window.location.href = "https://www.google.com";
        //do your next action here:

    }
}, 1000);

}

});

 </script>

2 个答案:

答案 0 :(得分:1)

您可以在点击功能上切换按钮,文档就像这样:

$( document ).ready(function() {
// Put relevant code here
}

答案 1 :(得分:1)

使用它。这将使用此部分代码

自动点击您的按钮
$(document).ready(function() {
  $(".butAfter").trigger("click");
});

反击开始了。

最终代码:

$(document).on("click", ".butAfter", function(e) {
  e.preventDefault();
  e.stopPropagation();

  if ($(this).hasClass('butstyle')) {

    $('.butstyle').text('You will be redirected in: 10 seconds');
    $(this).removeClass().addClass('butAfter');

    var int = setInterval(function() {
      counter--;
      $('.butAfter').text('You will be redirected in: ' + counter + ' seconds');

      if (counter == 0) {

        clearInterval(int);
        counter = 10;
        window.location.href = "https://www.google.com";
        //do your next action here:

      }
    }, 1000);

  }

});

$(document).ready(function() {
  $(".butAfter").trigger("click");
});

var counter = 10;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="myButton" class="butstyle butAfter" style="float:right">Click To Redirect</button>

相关问题