SoFunction
Updated on 2025-02-28

Switching delay when the js mouse passes through the tab tab

I accidentally discovered this effect when browsing the web page. When the mouse accidentally slides over the tab, it will not switch, and it will not switch after the mouse stays on it for a while.

I personally think that the user experience is good. The advantages are: 1. When the user just slides through the tag and does not need to switch. At this time, if the switch tag requires data to be requested, unnecessary asynchronous requests will be avoided; 2. Avoid the page switching and jumping when the user does not need it, affecting the user experience.

I looked up several methods online and found that the following methods are more concise and effective. Collected for future reference.

The key point is that piece of js code: the principle is to set the timer when hovering, delay the switching method, and clear the timer when leaving. When the time of the hover is less than the delay time, the timer will be clear and the switching method will not be performed. Switching only if the dwell time is greater than the delay time. This can effectively avoid sliding over the tab and triggering the switch event.

Copy the code

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="js/jquery.1.11."></script>
    <script>
      $(function() {
        var t_li = $(".tab")
        var c_li = $(".tab-content div")
        t_li.hover(function() {
          var i = t_li.index($(this));

          function way() {
            t_li.removeClass("cur").eq(i).addClass("cur");
            c_li.hide().eq(i).show();
          }
          timer = setTimeout(way, 500);
        }, function() {
          clearTimeout(timer);
        });
      });
    </script>
    <style>
      .head {
        width: 300px;
        height: 50px;
        border: 1px dashed #ccc;
      }
      
      .tab {
        width: 50%;
        float: left;
        line-height: 50px;
        cursor: pointer;
      }
      
      .cur {
        border-bottom: 2px solid red;
      }
    </style>
  </head>
  <body>
    <div style="width: 300px;margin-left: 300px;" class="main">
      <div class="head">
        <div class="tab cur">tab1</div>
        <div class="tab">tab2</div>
      </div>
      <div class="tab-content">
        <div>tab1Contents<br>tab1Contents<br>tab1Contents<br></div>
        <div style="display: none;">tab2Contents<br>tab2Contents<br>tab2Contents<br></div>
      </div>
    </div>
  </body>

</html>

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.