jQuery中mouseover和mouseout冒泡產生閃爍問題


問題:在jQuery中,對元素綁定mouseover和mouseout事件時,每次移入移出該元素和子元素時,都會觸發事件,從而會出現閃動的現象。

原因:瀏覽器的冒泡行為。

解決方案:

  1. 使用mouseenter事件和mouseleave事件分別代替mouseover事件和mouseout事件。

    例如有如下代碼:     

      <style>
         div{width: 50px;height: 50px;background:#ccc;}
         #test{background:red;width: 100px;height: 100px;}
      </style>
      <div id="test">
        <div></div>
      </div>
      <script>
        var test=document.getElementById("test");
        test.addEventListener("mouseover",function(){alert("aa");})
      </script>

如上代碼中,當你在test中的div上移入時也會觸發alert,只需把以上代碼中的mouseover改為mouseenter即可解決此問題。

   2.延遲執行(setTimeout)和取消執行(clearTimeout),就是當使用mouseover的時候延遲執行,當使用mouseout的時候取消延遲執行。

    例如代碼如下:

      test.onmouseover=function(){

         clearTimeout(t);    

         t=setTimeout(zoomIn,400);  

 

         alert("aa")

      };

      test.onmouseover=function(){   

         if(t!=null)clearTimeout(t);   

         t=null;

      } ;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM