单击并按住,然后重定向页面

时间:2019-06-13 04:01:27

标签: html css jss

帮我找出问题所在,我希望页面经过一定时间后重新定向,例如按住按钮2秒钟,但是如果时间未超过2秒钟,计时器将重置。而且只有在释放按钮之后,页面才会重定向。

在html中:

<div class="text-holder" id="button" style="display:none">
  <div class="body-border load"></div>
  <h2 class="text-holder-click show click-hold-anim">click and hold</h2>
  <h2 class="text-holder-hold hide hold-anim" id="text-hold">hold</h2>
</div>

JavaScript是:

 var timeout_id = 0,
     hold_menu = $('#button'),
     hold_time;

 hold_menu.mousedown(function () {
    timeout_id = setTimeout(hold_time);
    if (hold_time < 2000) {
    clearTimeout;
    } event.preventDefault();
 }).on('mouseup click', function () {
    clearTimeout(timeout_id);
    timeout_id = setTimeout(window_location, hold_time);
 });

 function window_location() {
 window.location.href = 'certain_page.html'
 };

1 个答案:

答案 0 :(得分:0)

如前所述,您可以像这样轻松地使用setTimeout和clearTimeout:

在这里,我已尝试使html与您的相似。为了进行测试,我摆脱了第二个h2,只保留了第一个。我已经删除了style =“ display:none”,所以我可以看到需要单击并按住的h2元素,并且向该h2元素添加了“ click-hold” ID,以便我们的jQuery侦听器可以触发< / p>

let timeout_id;
let time_passed = 0;

 $("#click-hold").on("mousedown", function (e) {
    e.preventDefault();
    //set interval when mouse is held down; it will increase time_passed by 1 every 1000ms(1s) and
    //append it to a div to show curr time passed
    timeout_id = setInterval(()=>{time_passed+=1; $("#append_here").empty().append(time_passed);}, 1000);
 });

 $("#click-hold").on('mouseup', function (e) {
   //button was released; clear interval that's been adding to time_passed
   clearInterval(timeout_id);
   
   //check if the time passed was greater or equal to 2(equivalent to 2s). This can be changed to 3,
   //4, 5, etc with each representing time elapsed in seconds. If condition is met, redirect. If not,
   //reset time_passed to 0
   if(time_passed >= 2){
      window.location.href="https://stackoverflow.com";
   }else{
      time_passed = 0;
   }
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
    <body style="text-align:center">
        <p>PAGE WILL REDIRECT AFTER 2s HOLDING TEXT BELOW</p>
        <div class="text-holder" id="button">
            <div class="body-border load"></div>
            <h2 class="text-holder-click show click-hold-anim" id="click-hold">CLICK AND HOLD</h2>
        </div>
        
        <p>Time Passed While Holding Text:</p>
        <div id="append_here">0</div>
    </body>
</html>

因此,当该元素处于按下状态时,超时从2000ms开始,一旦达到该时间,它将更改Windows url,就像您以前在单独的函数中一样。如果鼠标在任何时候都以id =“ click-hold”停留在该元素上,则该超时将被清除并且什么也不会发生。

我已经在自己的html文件中对其进行了测试,并且已经正常运行,因此请进一步询问是否存在某些问题