jQuery互動幫助方法

1. hover( over, out ) 

#hover函數主要解決在原始javascript中mouseover和mouseout函數存在的問題, 看下面這個範例:

image_thumb_6.png

有兩個div(紅色區域), 裡面分別巢狀了一個div(黃色區域). HTML程式碼如下:

  <div class="outer" id="outer1">
     Outer 1      <div class="inner" id="inner1">Inner 1</div>
   </div>
   <div class="outer" id="outer2">
     Outer 2      <div class="inner" id="inner2">Inner 2</div>
   </div>
   <div id="console">
</div>

綁定如下事件:

<script type="text/javascript">
     function report(event) {
       $('#console').append('<div>'+event.type+'</div>');
     }
     $(function(){
       $('#outer1')
        .bind('mouseover',report)
        .bind('mouseout',report);
       $('#outer2').hover(report,report);
     });    
</script>


Outer1我們使用了mouseover和mouseout事件,  當滑鼠從Outer1的紅色區域移動到黃色區域時, 會發現雖然都是在outer1的內部移動, 但是卻觸發了mouseout事件:

image_thumb_7.png

很多時候我們不希望出現上圖的結果,  而是希望只有滑鼠在Outer1內部移動時不觸發事件, Outer2使用Hover()函數實現了這個效果:

image_thumb_8.png

注意這裡的事件名稱進入叫做"mouseenter", 離開叫做"mouseleave", 而不再使用"mouseover"和"mouseleave"事件.

有經驗的開發人員會立刻想到在製作彈出式選單時, 經常遇到這個問題: 為彈出式選單設定了mouseout事件自動關閉, 但是滑鼠在彈出式選單內移動時常常莫名其妙觸發mouseout事件讓選單關閉. hover()函數幫助我們很好的解決了這個問題.

2. toggle( fn, fn2, fn3,fn4,... )

#toggle函數可以為物件新增click事件綁定函數,  但是設定每次點擊後依序的呼叫函數。

如果點擊了一個符合的元素,則觸發指定的第一個函數,當再次點擊相同元素時,則觸發指定的第二個函數,如果有更多函數,則再次觸發,直到最後一個。隨後的每次點擊都重複對這幾個函數的輪番呼叫。

可以使用unbind("click")來刪除。

下面的範例示範如何使用toggle函數:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head>
   <title>toggle example</title>
   <link rel="stylesheet" type="text/css" href="css/hover.css">
   <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
   <script type="text/javascript">
       $(function()
       {
           $("li").toggle(              function()
             {
                 $(this).css({ "list-style-type": "disc", "color": "blue" });
             },              function()
             {
                 $(this).css({ "list-style-type": "square", "color": "red" });
             },              function()
             {
                 $(this).css({ "list-style-type": "none", "color": "" });
             }
           );
       })    </script></head><body>
   <ul>
       <li style="cursor:pointer">click me</li>
   </ul>
</body>
</html>


結果是每點擊一次"click me"變換一次列表符號和文字顏色.


#
繼續學習
||
<html> <head> <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".btn1").click(function(){ $("p").toggle(); }); }); </script> </head> <body> <p>This is a paragraph.</p> <button class="btn1">Toggle</button> </body> </html>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!