????:做動(dòng)畫(huà)時(shí),需要判斷鼠標(biāo)進(jìn)入和退出容器的方向。網(wǎng)上找到的基于JQuery的實(shí)現(xiàn)方法,用函數(shù)封裝了一下,寫(xiě)了一個(gè)示例。注意綁定鼠標(biāo)事件用的是on(),所以JQuery版本需高于1.7。<!DOCTYPE html> <html> <head> <meta charset="UTF-8"
做動(dòng)畫(huà)時(shí),需要判斷鼠標(biāo)進(jìn)入和退出容器的方向。網(wǎng)上找到的基于JQuery的實(shí)現(xiàn)方法,用函數(shù)封裝了一下,寫(xiě)了一個(gè)示例。注意綁定鼠標(biāo)事件用的是on(),所以JQuery版本需高于1.7。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>判斷鼠標(biāo)從哪個(gè)方向進(jìn)入和離開(kāi)容器</title> <script src="js/jquery-3.1.1.min.js"></script> <style> *{border: 0;margin: 0;padding: 0;} .item{width: 300px; height: 200px;border: 1px solid #999;margin: 50px;} </style> </head> <body> <div class="item"> </div> <p id="info"></p> </body> <script> /** * 判斷鼠標(biāo)從哪個(gè)方向進(jìn)入和離開(kāi)容器 * @param {Object} tag JQuery對(duì)象,事件綁定的主體 * @param {Object} e event對(duì)象 * @return {Number} direction 值為“0,1,2,3”分別對(duì)應(yīng)著“上,右,下,左” */ function moveDirection(tag,e){ var w = $(tag).width(); var h = $(tag).height(); var x = (e.pageX - tag.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1); var y = (e.pageY - tag.offsetTop - (h / 2)) * (h > w ? (w / h) : 1); var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; return direction; } //使用方法 $(".item").on("mouseenter mouseleave", function (e) { var eType = e.type; var direction = moveDirection(this,e); var dirName = new Array("上","右","下","左"); if(eType == "mouseenter"){ $("#info").text("鼠標(biāo)從"+dirName[direction]+"方進(jìn)入方框"); }else if(eType == "mouseleave"){ $("#info").text("鼠標(biāo)從"+dirName[direction]+"方離開(kāi)方框"); } }); </script> </html>
更多關(guān)于JQuery獲取鼠標(biāo)進(jìn)入和離開(kāi)容器的方向請(qǐng)關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!