【问题标题】:Is it possible to get the mouse position only relative to your element是否可以仅相对于您的元素获取鼠标位置
【发布时间】:2019-08-24 18:34:54
【问题描述】:

如果我在给定元素中有多个子元素,则无法获取鼠标相对于附加事件的元素位置。

domElement.addEventListener('wheel', event => {
 event.offsetX //x relative to target element
 event.offsetY //y relative to target element
}

如果我的鼠标悬停在一个子元素上,它会给出子元素的位置。我知道 event.pageX 或 event.clientX 但它给了我相对于窗口/视口的鼠标位置。

const element = document.getElementById("wrapper");
const output = document.getElementById("output");
element.addEventListener("wheel", event =>{
output.innerHTML = `offsetX: ${event.offsetX}, offsetY: ${event.offsetY}`;
});
#wrapper{
  height:300px;
  width:500px;
  background:#ccc;
  position:absolute;
  left:400px;
  top:20px;
}

#child{
  position:relative;
  height:120px;
  width:130px;
  left:50px;
  top:120px;
  background: green;
}
<div id="wrapper">
  <div id="child">
  </div>
</div>

<div id="output"></div>

【问题讨论】:

    标签: javascript html mouseevent mousewheel mouse-position


    【解决方案1】:

    你可以使用这个:https://developer.mozilla.org/es/docs/Web/API/Element/getBoundingClientRect 获取元素的位置,然后就是一个简单的操作。

    【讨论】:

    • 是的 +1。这是我自己找到的解决方案。
    【解决方案2】:

    欢迎来到 Stack Overflow!

    如果您将此 CSS 属性设置为您的子元素:

    pointer-events: none;
    

    滚轮位置将始终相对于父元素,但请记住,它将禁用所有鼠标与子元素的交互。

    您可以在此处找到更多信息: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

    【讨论】:

    • 感谢您的回答,但不幸的是,我必须能够在我的子元素中使用不同的鼠标事件。像“点击”事件
    【解决方案3】:

    我找到了一个我不太喜欢的解决方案。函数getBoundingClientRect ()

    const element = document.getElementById("wrapper");
    const output = document.getElementById("output");
    element.addEventListener("wheel", event =>{
       let { x, y } = element.getBoundingClientRect();
       let position = { x, y };
       let mousex = event.clientX - position.x;
       let mousey = event.clientY - position.y;
    output.innerHTML = `offsetX: ${mousex}, offsetY: ${mousey}`;
    });
    #wrapper{
      height:300px;
      width:500px;
      background:#ccc;
      position:absolute;
      left:400px;
      top:20px;
    }
    
    #child{
      position:relative;
      height:120px;
      width:130px;
      left:50px;
      top:120px;
      background: green;
    }
    <div id="wrapper">
      <div id="child">
      </div>
    </div>
    
    <div id="output"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-18
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多