1. 判断鼠标进入 div 的方向

<!DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    .demo {
      width: 400px;
      height: 300px;
      background-color: pink;
      margin: 100px auto;
    }
  </style>
  <script src="js/jquery-1.11.3.min.js"></script>
  <script type="text/javascript">
    $(function () {
      $('div').on('mouseenter mouseleave', function (e) {
        var w = $(this).width(); // 得到盒子宽度
        var h = $(this).height(); // 得到盒子高度
        var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
        var y = (e.pageY - this.offsetTop - (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”分别对应着“上,右,下,左”
        // 将点的坐标对应的弧度值换算成角度度数值
        var dirName = new Array('上方', '右侧', '下方', '左侧');
        if (e.type == 'mouseenter') {
          $(this).html(dirName[direction] + '进入');
        } else {
          $(this).html(dirName[direction] + '离开');
        }
      });
    })
  </script>
</head>

<body>
  <div class="demo"></div>
</body>

</html>
Copyright © Guanghui Wang all right reserved,powered by GitbookFile Modified: 2019-08-25 13:56:34

results matching ""

    No results matching ""