JSFiddle - React, Tailwind, and code Playground
HTML
<div id="test"></div>
CSS
#test{
width:300px;
height:200px;
border:1px solid red;
}
JavaScript
var target=document.getElementById('test');
//得到鼠标进入元素的方向
function showDirection(e){
//1、获取元素的宽高
var
width=target.offsetWidth,
height=target.offsetHeight;
//2、计算鼠标在以元素中心为原点的坐标系中的位置,并矫正位置
var
x=(e.clientX-target.offsetLeft-width/2)*(width>height?(height/width):1),
y=(e.clientY-target.offsetTop-height/2)*(height>width?(width/height):1);
//3、计算方向(智商不足,没完全理解)
/*
* 3.1 atan2函数是计算点(x,y)与坐标系原点形成的线段与X轴的夹角 取值(-π,π)
* 3.2 乘以(180/Math.PI)是将弧度装成角度
* 3.3 加上180是为了消除负值对结果的影响
* 3.4 除以90是为了判断当前鼠标在哪个象限
* 3.5 加3对4取模 是为了把象限转换成合适的顺时针方向(上、右、下、左)
*
* 计算结果为0、1、2、3分别对应上、右、下、左
*/
var
direction=Math.round((((Math.atan2(y,x)*(180/Math.PI))+180)/90)+3)%4,
dirName=['上','右','下','左'];
if('mouseover'===e.type || 'mouseenter'===e.type){
target.innerHTML='从【'+dirName[direction]+'】进入';
}else{
target.innerHTML='从【'+dirName[direction]+'】离开';
}
}
//事件监听
if(window.addEventListener){//DOM标准
target.addEventListener('mouseover',showDirection,false);
target.addEventListener('mouseout',showDirection,false);
}else if(window.attachEvent){//IE
target.attachEvent('onmouseenter',showDirection);
target.attachEvent('onmouseleave',showDirection);
}