如何在相对定位的元素内获取鼠标的坐标

How to get the coordinates of the mouse inside a relatively positioned element?

本文关键字:获取 鼠标 坐标 元素 相对 定位      更新时间:2023-09-26

我想将元素$menu放置在鼠标指针上(单击时(。 $menu在里面$icon里面有position: relative。($menu具有绝对位置。

$(document).ready(function() {
  $("a").click(function(ev) {
    var $icon = $(ev.currentTarget)
    var $menu = $icon.next()
    var thisPos = $icon.position()
    var x = ev.clientX
    var y = ev.clientY
    $menu.css('top', y + 'px')
    $menu.css('left', x + 'px')
  });
})
nav > ul[_v-2e9e2f12] {
  background: #3a3c3a;
  margin: 0;
  padding: 10px;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  z-index: 9999;
  box-shadow: 2px 0 1px rgba(0, 0, 0, 0.1);
}
nav > ul li[_v-2e9e2f12] {
  display: block;
  margin: 0 0 8px;
  text-align: center;
  position: relative;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
  width: 48px;
  height: 48px;
  background: #ccc;
}
ul[_v-0078ee36] {
  background: #3a3c3a;
  position: absolute;
  border-radius: 3px;
  box-shadow: 0 2px 1px rgba(0, 0, 0, 0.1);
}
a[_v-2e9e2f12] {
  display: block;
  width: 48px;
  height: 48px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <ul _v-2e9e2f12="">
    <li _v-2e9e2f12="">
      <a _v-2e9e2f12="">
      </a>
      <ul _v-0078ee36="" _v-2e9e2f12="">
        Hello!
      </ul>
    </li>
    <li _v-2e9e2f12="">
      <a _v-2e9e2f12="">
      </a>
      <ul _v-0078ee36="" _v-2e9e2f12="">
        Hello!
      </ul>
    </li>
  </ul>
</nav>

但是我得到了一个奇怪的行为:$menu没有定位在鼠标的指针上,而是位于右侧和底部的几个像素上。对于第二个元素,情况更糟:右侧和底部有许多像素。

如何解决此问题,并使$menu位于鼠标指针中?

这是JSFiddle。

使用 offsetXoffsetY 而不是 client

var x = ev.offsetX;
var y = ev.offsetY;

演示