javscript判断鼠标进入方向
之前在别的网站上看到过判断鼠标进入方向然后展示一些效果的例子,以下是我整理的一个比较简单一点的判断鼠标进入方向的例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>javscript判断鼠标进入方向</title>
</head>
<body>
<div id="xx" style="width:100px;height:100px;border:1px solid #f00;margin:100px"></div>
<span id="status"></span>
<script type="text/javascript">
(function(){
var $div = document.querySelector("#xx"),$status = document.querySelector("#status"),w = $div.offsetWidth,h = $div.offsetHeight,t = $div.offsetTop,l = $div.offsetLeft;
$div.addEventListener("mouseenter",handler,false);
$div.addEventListener("mouseleave",handler,false);
function handler(e){
var e = e || window.event,
x = e.pageX - l - (w/2) * (w>h ? h/w : 1),
y = e.pageY - t - (h/2) * (h>w ? w/h :1),
direction = Math.round((Math.atan2(y,x)*(180/Math.PI)+180)/90+3)%4;
$status.innerText = ["上方","右方","下方","左方"][direction] + (e.type=="mouseenter"?"进入":"离开");
}
})();
</script>
</body>
</html>-
支付宝 -
微信


