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

时间:2022-06-24 20:22:18

I want to position an element $menu on the mouse's pointer (on click). $menu is inside $icon which has position: relative. ($menu has position absolute.)

我想在鼠标指针上(单击)放置一个元素$菜单。$菜单在$图标内,它有位置:相对。(美元菜单位置绝对的。)

$(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>

But I get a weird behavior: $menu is not positioned on the mouse's pointer but a few pixels to the right and bottom. And for the second element it's even worse: many pixels to the right and bottom.

但我得到了一个奇怪的行为:$menu不是位于鼠标指针上,而是位于右下角的几个像素。对于第二个元素,它甚至更糟:在右边和底部有许多像素。

How to fix this, and make $menu to be positioned right in the mouse's pointer?

如何解决这个问题,并使$菜单被放置在鼠标指针中?

Here's the JSFiddle.

这是JSFiddle。

1 个解决方案

#1


3  

Use offsetX and offsetY instead of client's

使用offsetX和offsetY代替客户的

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

DEMO

#1


3  

Use offsetX and offsetY instead of client's

使用offsetX和offsetY代替客户的

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

DEMO