从 iframe 获取包含父页面的点击坐标

问题描述 投票:0回答:1

我的页面中有一个 iframe,当我单击它时,我会显示一个包含信息的小方块。问题是 iframe 通过发布消息给出的坐标是正确的,除非在其中滚动,因为坐标大于父视图高度。我想知道如何进行计算以便将其显示在正确的位置。

我已经尝试使用客户端矩形和滚动坐标来计算 newY 。问题是滚动坐标始终为 0,因此不会对计算产生影响。这是我的使用效果:

useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data.type === 'toolInfo' && footprintsOn) {
        const iframe = document.getElementById('titanpad') as HTMLIFrameElement;
        const iframeRect = iframe.getBoundingClientRect();
        const { x: iframeX, y: iframeY } = iframeRect;
        const iframeScrollTop = event.data.data.scrollCoordinates.scrollY;
        
        const newX = event.data.data.coordinates.x + iframeX;
        let newY = event.data.data.coordinates.y + iframeY + iframeScrollTop;
        
        // Adjust newY if it's beyond the current view bounds
        const maxYInView = window.innerHeight + window.scrollY;
        console.log(maxYInView, window.innerHeight, window.scrollY, newY)
        if (newY > maxYInView) {
          newY = maxYInView;
        }

        event.data.data.coordinates = { x: newX, y: newY };
        setToolInfoSquareData(event.data);
        setOpenToolInfo(true);
      } 
    };

    window.addEventListener('message', handleMessage);

    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, [footprintsOn]);

我的计算中是否漏掉了一些东西?或者解决这个问题的正确方法是什么。

我想要类似以下示例的内容。在这种情况下,文本文档将是 iframe,即使它向下滚动,我也希望正方形出现在同一级别。 (使用我现在所拥有的,如果我单击文本并且已经向下滚动,正方形会出现在视图高度边界之外,并将常规滚动应用于父页面。我只希望 iframe 具有滚动):

reactjs iframe onclick coordinates
1个回答
0
投票

您是否尝试过使用

document.scrollTop
而不是
window.scrollY
作为 iframe 的滚动值。

您没有显示如何在 iframe 中获取滚动位置的代码,因此很难进一步评论。

© www.soinside.com 2019 - 2024. All rights reserved.