js判斷鼠標移入移出方向

 前段時間,偶然看到百度百科裏面,有一DIV反轉的效果,試了一個竟然能夠根據鼠標移入移出的方向,進行不一樣的反轉;因此,內心就犯嘀咕,起了疑惑,一個DIV容器如何知道鼠標移入移出方向,進而產生不一樣的行爲:如圖所示:javascript

wKiom1SQM_ij7OKoAACdS-1LWU8037.jpg

本身試了一下,網上網友說的用4個div牢牢包裹住容器,以下所示:html

wKioL1SQNTyhr9j0AACzkXHoPSo816.jpg

這中作法在移入,移出的速度過快時,有bug很差用;java

最後在一篇博客裏面找到了一個比較好的方法:代碼以下jquery

$("#wrap").bind("mouseenter mouseleave",
function(e) {
var w = $(this).width();
var h = $(this).height();
var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);
var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
var eventType = e.type;
var dirName = new Array('上方','右側','下方','左側');
if(e.type == 'mouseenter'){
$(this).html(dirName[direction]+'進入');
}else{
$(this).html(dirName[direction]+'離開');
}
});


充分利用幾何數學實現了這個功能,真心不錯;分享給你們,演示代碼以下:ide



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>判斷鼠標進入方向</title>
</head>
<body>
<style>
html,body{margin:0;padding:0;}
#wrap{width:300px;height:300px;background:#33aa00;margin:50px;display:inline-block;font-size:50px;text-align:center;line-height:300px;}
</style>
<div id="wrap">
 方向反饋
</div>
<script type="text/javascript" src="http://common.cnblogs.com/script/jquery.js"></script>
<script>
$("#wrap").bind("mouseenter mouseleave",
function(e) {
var w = $(this).width();
var h = $(this).height();
var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);
var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
var eventType = e.type;
var dirName = new Array('上方','右側','下方','左側');
if(e.type == 'mouseenter'){
$(this).html(dirName[direction]+'進入');
}else{
$(this).html(dirName[direction]+'離開');
}
});
</script>
</body>
</html>
相關文章
相關標籤/搜索