- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在更新 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.)
});
听起来像个错误?
更新:
重现步骤:
cfx xpi
从源安装)(在 Github 的当前代码中,我将 e.button === 2
检查注释掉了,但结果是一样的。)
最佳答案
原来 MDN 上的文档是完全错误的。 .caretPositionFromPoint
期望 you pass coordinates relative to the current viewport .
所以你必须使用e.clientX
/e.clientY
!
此外,.mozInnerScreenX
/Y
不会执行您可能期望的操作。如果要检查 x
和 y
是视口(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/
我正在更新 my "jump-to-anchor" add-on这是一个 Firefox 附加组件,可让您右键单击文档中的某处以(希望)获得点击点上方最近的 anchor 。 提交附加组件后,我意识到
我是一名优秀的程序员,十分优秀!