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

Click and Hold then redirecting the page

帮我找出问题所在,我希望页面在一定时间后重定向,假设 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'
 };

如上所述,您可以轻松地使用 setTimeout 和 clearTimeout:

在这里,我尽量使 html 与您的相似。出于测试目的,我去掉了第二个 h2,只保留了第一个。我已经删除了 style="display:none" 这样我就可以看到需要单击并按住的 h2 元素,并且我已经将 "click-hold" 的 id 添加到那个 h2 元素所以我们的 jQuery听众可以开火

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://whosebug.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>

因此,当按住该元素时,超时从 2000 毫秒开始,一旦达到该时间,它将更改 windows url,就像您之前在单独的函数中所做的那样。如果在任何时候鼠标移动到 id="click-hold" 的那个元素上,该超时将被清除并且什么都不会发生。

我已经在我自己的 html 文件中对此进行了测试并且它工作正常,所以请进一步询问是否有问题