基於JQuery的擷取滑鼠進入和離開容器方向的實現

來源:互聯網
上載者:User

標籤:min   padding   char   tag   code   樣本   ret   else   rip   

基於JQuery的擷取滑鼠進入和離開容器方向的實現

 

 做動畫時,需要判斷滑鼠進入和退出容器的方向。網上找到的基於JQuery的實現方法,用函數封裝了一下,寫了一個樣本。注意綁定滑鼠事件用的是on(),所以JQuery版本需高於1.7。

 1 <!DOCTYPE html> 2 <html> 3     <head> 4         <meta charset="UTF-8"> 5         <title>判斷滑鼠從哪個方向進入和離開容器</title> 6         <script src="js/jquery-3.1.1.min.js"></script> 7         <style> 8             *{border: 0;margin: 0;padding: 0;} 9             .item{width: 300px; height: 200px;border: 1px solid #999;margin: 50px;}10         </style>11     </head>12     <body>13         <div class="item">14         </div>15         <p id="info"></p>16     </body>17     <script>18         /**19          * 判斷滑鼠從哪個方向進入和離開容器20          * @param {Object} tag JQuery對象,事件綁定的主體21          * @param {Object} e   event對象22          * @return {Number} direction 值為“0,1,2,3”分別對應著“上,右,下,左”23          */24         function moveDirection(tag,e){25             var w = $(tag).width();26             var h = $(tag).height();27             var x = (e.pageX - tag.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);28             var y = (e.pageY - tag.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);29             var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; 30             return direction;31         }32         //使用方法33         $(".item").on("mouseenter mouseleave", function (e) {34             var eType = e.type;35             var direction = moveDirection(this,e);36             var dirName = new Array("上","右","下","左");37             if(eType == "mouseenter"){38                 $("#info").text("滑鼠從"+dirName[direction]+"方進入方框");39             }else if(eType == "mouseleave"){40                 $("#info").text("滑鼠從"+dirName[direction]+"方離開方框");41             }42         });43     </script>44 </html>

基於JQuery的擷取滑鼠進入和離開容器方向的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.