【问题标题】:How do i find where the button is clicked so that I can position something over there?我如何找到单击按钮的位置以便我可以在那里放置一些东西?
【发布时间】:2021-09-11 13:39:30
【问题描述】:

我希望弹出窗口或模态框或 toast 出现在单击按钮的正确位置。 但我无法找到任何关于此的内容。我能找到的任何东西都类似于,它出现在中心或顶部或预定义的东西我猜仍然不正确单击按钮的位置。 应该如何处理?

【问题讨论】:

  • 您在寻找类似tooltip 的东西吗?

标签: javascript reactjs modal-dialog popup toast


【解决方案1】:

https://reactjs.org/docs/events.html#mouse-events

onClick 回调中的 MouseEvent 参数包含点击的 x 和 y 坐标。

const handleClick = (mouseEvent) => {
    console.log(`x = ${mouseEvent.clientX}, y = ${mouseEvent.clientY}`)
}

React 提供了 3 种不同的坐标客户端、页面和屏幕,上面的示例使用了客户端坐标。您可以在MDN Web Docs

中阅读更多关于它们的区别

【讨论】:

    【解决方案2】:
    const box = document.querySelector('#box');
    
    box.addEventListener('click', function(event) {
        console.log(`Horizontal: ${clientX}, Vertical: ${clientY}`);
        // Take Position Current onClick
    });
    

    你可以通过clientY设置top,clientX从事件监听器离开

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      相关资源
      最近更新 更多