(编辑:jimmy 日期: 2024/12/27 浏览:2)
PC端鼠标移入移出的效果很好,这里就给出判断鼠标移入移出的方法,有空再发出带效果的文章,不过授之以鱼不如受之以渔,有了个这个方法,效果不还是so easy吗?
代码:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> <style type="text/css"> * { padding: 0; margin: 0; } .ul-box { width: 345px; margin: 20px auto; background-color: #f5f5f5; overflow: auto; } .li-item { width: 100%; height: 134px; margin-bottom: 10px; border-radius: 4px; } .li-item1 { background: linear-gradient(90deg, #7f90e3 0%, #8b9bff 100%); } </style> </head> <body> <ul id="ulBox" class="ul-box"> <li class="li-item li-item1" onmouseleave="derEvent(event, 'leave')" onmouseenter="derEvent(event, 'enter')"></li> </ul> </body> <script type="text/javascript"> /** * @param {Object} event 当前事件源信息 * @return {Number} d 方向 top 0 right 1 bottom 2 left 3 */ function getDer(event) { let ele = event.target var d; var w = ele.offsetWidth, h = ele.offsetHeight, l = ele.offsetLeft, t = ele.offsetTop, x = (event.clientX - l - w / 2) * (w > h ? (h / w) : 1), y = (event.clientY - t - h / 2) * (h > w ? (w / h) : 1); d = (Math.round((Math.atan2(y, x) * (180 / Math.PI) + 180) / 90) + 3) % 4; return d; // top 0 right 1 bottom 2 left 3 } /** * @param {Object} event 事件源信息 * @param {Object} type 类型 leave 离开 色 enter 进入 */ function derEvent(event, type) { let d = getDer(event) let txt = '' switch (d) { case 0: txt = '上' break; case 1: txt = '右' break; case 2: txt = '下' break; case 3: txt = '左' break; default: break; } if (type === 'leave') { console.log(txt, '离开') } else { console.log(txt, '进入') } } </script> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。