
js实现鼠标移入元素方向主要原理就是利用坐标系计算鼠标移入元素时当前的角度然后通过夹角范围判断鼠标移入元素的具体方向。代码如下!doctype html html langzh-CN head meta charsetUTF-8 / meta nameviewport contentwidthdevice-width, initial-scale1.0 / title判断鼠标进入元素方向demo/title style * { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif; } #app { position: relative; width: 400px; height: 200px; overflow: hidden; line-height: 200px; text-align: center; font-size: 50px; background-color: #eee; margin: 200px auto; } #app div { position: absolute; width: 400px; height: 200px; font-size: 30px; color: #fff; text-align: center; background-color: rgba(0, 0, 0, 0.7); transition: all 0.3s ease-in-out; } .top { top: -200px !important; } .top.active { top: 0 !important; } .bottom { top: 200px !important; } .bottom.active { top: 0 !important; } .left { left: -400px !important; } .left.active { left: 0 !important; } .right { left: 400px !important; } .right.active { left: 0 !important; } /style /head body div idapp div classtoptop/div div classbottombottom/div div classleftleft/div div classrightright/div /div /body /html script const app document.getElementById(app); const leftx app.getBoundingClientRect().left; const topy app.getBoundingClientRect().top; const width app.getBoundingClientRect().width; const height app.getBoundingClientRect().height; let miring Math.sqrt(height * height width * width) / 2; // 对角线的一半 let x leftx width / 2; // 坐标轴xy的坐标 let y topy height / 2; let miringAngle Math.atan((height / 2) / (width / 2)) * (180 / Math.PI); // 对角线的角度 app.addEventListener(mouseenter, (event) { let x1 event.clientX - x; // 当前坐标点x坐标 let y1 -(event.clientY - y); // 当前坐标点y坐标 // let currentAngle Math.asin(y1 / miring) * (180 / Math.PI); // 当前正弦函数求角度 let angle Math.atan(y1 / x1) * (180 / Math.PI); // 正弦函数求角度, 当前鼠标移入的角度 console.log(进入的坐标点, x1, y1); if (x1 0 y1 0) { angle angle; // 第一象限 } else if (x1 0 y1 0) { angle 180 angle; // 第二象限 } else if (x1 0 y1 0) { angle 180 angle; // 第三象限 } else if (x1 0 y1 0) { angle 360 angle; // 第四象限 } console.warn(鼠标进入的角度, angle); if (angle miringAngle angle 180 - miringAngle) { console.log(从上方进入); document.querySelector(.top).classList.add(active); // app.innerHTML 从上方进入; } else if (angle 180 - miringAngle angle miringAngle 180) { console.log(从左边进入); document.querySelector(.left).classList.add(active); // app.innerHTML 从左边进入; } else if (angle miringAngle 180 angle 360 - miringAngle) { console.log(从下边进入); document.querySelector(.bottom).classList.add(active); // app.innerHTML 从下边进入; } else { console.log(从右边进入); document.querySelector(.right).classList.add(active); // app.innerHTML 从右边进入; } }); // 鼠标离开元素时移除active类 app.addEventListener(mouseleave, () { // app.innerHTML 离开了; app.querySelector(#app .active).classList.remove(active); }); /script运行结果