首页 > 代码库 > 判断鼠标的移入方向
判断鼠标的移入方向
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style media="screen"> body { height: 3000px; } * { padding: 0; margin: 0; } ul { list-style: none; position: relative; font-size: 0; width: 600px; margin: 50px auto 0; } ul>li { position: relative; width: 300px; height: 300px; background-color: rgb(213, 213, 213); display: inline-block; margin: 10px; overflow: hidden; } ul>li .bg { position: absolute; width: 100%; height: 100%; left: -100%; top: 0; background-color: red; text-align: center; line-height: 300px; cursor: pointer; color: #fff; font-size: 20px; } .line { position: absolute; width: 50%; height: 1px; background: red; right: 0; top: 50%; transition: all .3s; transform-origin: left; } .res { text-align: center; } ul>li.fix { width: 200px; height: 300px; } </style> </head> <body> <ul> <li> <div class="bg"> 111111111111 </div> </li> <li class="fix"> <div class="bg"> 22222222222222 </div> </li> <li> <div class="bg"> 333333333333 </div> </li> </ul> <div class="res"></div> <script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script> <script> $("li").on("mouseenter mouseleave", function(e) { var $bg = $(this).find(‘.bg‘); var w = this.offsetWidth; //获取元素宽度 var h = this.offsetHeight; //获取元素高度 var toTop = this.getBoundingClientRect().top + document.body.scrollTop; //兼容滚动条 var x = (e.pageX - this.getBoundingClientRect().left - (w / 2)) * (w > h ? (h / w) : 1); //获取当前鼠标的x轴位置(相对于这个li的中心点) var y = (e.pageY - toTop - h / 2) * (h > w ? (w / h) : 1); var direction = Math.round((((Math.atan2(y, x) * 180 / Math.PI) + 180) / 90) + 3) % 4; //direction的值为“0,1,2,3”分别对应着“上,右,下,左” // /90矩形矫正 成正方形---》 为正方形的情况 // Math.round(x/90) --->(0,1) + 3 刚好对应四个象限 var eventType = e.type; var res = Math.atan2(y, x) / (Math.PI / 180) + 180; // +180 ------》 (-180,180) -----》(0,360) // $(‘.line‘).css(‘transform‘, ‘rotate(‘ + res + ‘deg)‘); var dirName = [‘上方‘, ‘右侧‘, ‘下方‘, ‘左侧‘]; if (eventType == ‘mouseenter‘) { $(‘.res‘).text(dirName[direction] + ‘进入‘); animationIn(direction, $bg); } else { $(‘.res‘).text(dirName[direction] + ‘离开‘); animationOut(direction, $bg); } }); function animationIn(direction, ele) { switch (direction) { case 0: ele.css({ left: 0, top: ‘-100%‘ }).stop().animate({ top: 0 }, 300); break; case 1: ele.css({ left: ‘100%‘, top: 0 }).stop().animate({ left: 0 }, 300); break; case 2: ele.css({ left: 0, top: ‘100%‘ }).stop().animate({ top: 0 }, 300); break; case 3: ele.css({ left: ‘-100%‘, top: 0 }).stop().animate({ left: 0 }, 300); break; } } function animationOut(direction, ele) { switch (direction) { case 0: ele.stop().animate({ top: ‘-100%‘ }, 300); break; case 1: ele.stop().animate({ left: ‘100%‘ }, 300); break; case 2: ele.stop().animate({ top: ‘100%‘ }, 300); break; case 3: ele.stop().animate({ left: ‘-100%‘ }, 300); break; } } </script> </body> </html>
判断鼠标的移入方向
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。