gpt4 book ai didi

javascript - 获取准确的浏览器渲染文本(RTL 和 LTR 方向混合)

转载 作者:行者123 更新时间:2023-12-03 04:01:43 25 4
gpt4 key购买 nike

有没有办法检索浏览器实际呈现的文本(在从右到左文本方向的上下文中)?

<html dir="rtl">
<body>
<p id='ko'>Hello (world)</p>
<p id='ok'>Hello <bdo dir='ltr'>(world)</bdo></p>
</body>
</html>

将渲染:

  • 在 Chrome 中

enter image description here

  • 在火狐浏览器

enter image description here

但是两者document.getElementById('ok').textContent === document.getElementById('ko').textContentdocument.getElementById('ok').innerText === document.getElementById('ko').innerTexttrue(对于两种浏览器)。

有没有办法获取网页中显示的实际文本?

https://jsfiddle.net/019kvo56/1/

最佳答案

有一个 direction CSS 属性,您可以从 getCompulatedStyle(elem) 中获取,但这仅在元素级别,因此您无法确切知道浏览器如何渲染文本节点。

所以你需要做的是:

  • 首先从容器中获取所有 textNode(最好使用 TreeWalker 来完成)。
  • 使用 Range object 选择每个字符
  • 通过 Range 的 getBoundingClientRect() 获取每个 Angular 色的当前位置方法。
  • 对它们进行排序
  • 取回它们的文本值

这是一个现场演示:

function getDisplayedText(container) {

var r = document.createRange(); // to get our nodes positions

var nodes = []; // first grab all the nodes
var treeWalker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, null, false);
while (treeWalker.nextNode()) nodes.push(treeWalker.currentNode);

var chars = []; // then get all its contained characters
nodes.forEach(n => {
n.data.split('').forEach((c, i) => {
r.setStart(n, i); // move the range to this character
r.setEnd(n, i+1);
chars.push({
text: c,
rect: r.getBoundingClientRect() // save our range's DOMRect
})
})
});

return chars.filter(c => c.rect.height) // keep only the displayed ones (i.e no script textContent)
.sort((a, b) => { // sort ttb ltr
if (a.rect.top === b.rect.top) {
return a.rect.left - b.rect.left;
}
return a.rect.top - b.rect.top;
})
.map(n => n.text)
.join('');
}

console.log('ko : ', getDisplayedText(ko));
console.log('ok : ', getDisplayedText(ok));
<div dir="rtl">
<p id='ko'>Hello (world)</p>
<p id='ok'>Hello <bdo dir='ltr'>(world)</bdo></p>
</div>

现在,至于为什么 webkit 会渲染最后一个 ) 翻转和第一个...我不知道他们这样做是否正确...

关于javascript - 获取准确的浏览器渲染文本(RTL 和 LTR 方向混合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44695297/

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