gpt4 book ai didi

javascript - document.caretPositionFromPoint 抓得太高

转载 作者:行者123 更新时间:2023-11-30 17:25:35 40 4
gpt4 key购买 nike

我正在更新 my "jump-to-anchor" add-on这是一个 Firefox 附加组件,可让您右键单击文档中的某处以(希望)获得点击点上方最近的 anchor 。

提交附加组件后,我意识到我可以通过找到被单击的实际文本节点并从那里查找(而不是当前被单击元素的第一个子元素)来改进算法。但是,在我的测试中(针对我碰巧正在阅读的页面 https://www.rfc-editor.org/rfc/rfc5323#section-2.3.2 ),文本节点通过 document.caretPositionFromPoint 抓取高于预期。

var x = 0, y = 0;
window.addEventListener('click', function (e) {
if (e.button === 2) { // Avoid grabbing for the actual selection // Doesn't seem to execute on the final context menu click anyways
x = e.pageX;
y = e.pageY;
}
});
self.on('click', function () { // , data
// I added the next two lines just in case the user clicked off screen
x = x > window.mozInnerScreenX ? window.mozInnerScreenX : (x < 0 ? 0 : x);
y = y > window.mozInnerScreenY ? window.mozInnerScreenY : (y < 0 ? 0 : y);
var caretPosition = document.caretPositionFromPoint(x, y);
var node = caretPosition.offsetNode;

// Doesn't grab the right node.nodeValue here always--seems to grab too high up

// (Then search the node for an anchor, or recursively check the deepest child of the previous element sibling on up and keep looking for previous element siblings.)
});

听起来像个错误?

更新:

重现步骤:

  1. https://github.com/brettz9/jump-to-anchor/tree/document.caretPositionFromPoint 安装 XPI (或使用带有 SDK 的 cfx xpi 从源安装)
  2. 转到 https://www.rfc-editor.org/rfc/rfc5323#section-2.3.2
  3. 尝试在第 2.3.3 节(注意:2.3.3)内单击鼠标右键,发现它经常一直移动到“#page-10” anchor 而不是“#section-2.3.3” anchor 。

(在 Github 的当前代码中,我将 e.button === 2 检查注释掉了,但结果是一样的。)

最佳答案

原来 MDN 上的文档是完全错误的。 .caretPositionFromPoint 期望 you pass coordinates relative to the current viewport .

所以你必须使用e.clientX/e.clientY!

此外,.mozInnerScreenX/Y 不会执行您可能期望的操作。如果要检查 xy 是视口(viewport)内的有效坐标,请使用 window.innerWidth/.innerHeight .

所以这是我尝试过的并且似乎有效的方法(摘录):

var x = 0, y = 0;
window.addEventListener('click', function (e) {
x = e.clientX;
y = e.clientY;
});
self.on('click', function () { // , data
x = Math.max(0, Math.min(innerWidth, x));
y = Math.max(0, Math.min(innerHeight, y));
var caretPosition = document.caretPositionFromPoint(x, y);
var node = caretPosition.offsetNode;
// ...
});

关于javascript - document.caretPositionFromPoint 抓得太高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24360624/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com