本质上,我正在尝试实现一项功能,该功能在选中时突出显示某些文本。这仅适用于Google Chrome浏览器。
例如:选择之前:
<html>
<body>
<p>sample text</p>
</body>
</html>
从“示例文本”中选择“文本”后:
<html>
<body>
<p>sample <span class="state-highlighted">text</span> </p>
</body>
</html>
JavaScript:
document.body.addEventListener("mousedown", (event) => {
document.body.addEventListener("mouseup", (event) => {
// Assume we have checked that mousedown position is different from mouseup position.
// Not sure what to do after this.
});
});
我可以从一个简单的问题开始:我如何将span元素插入paragragh元素中,比如说单击?
这里有一种Range.surroundContents
方法很方便,但是仅选择元素的一部分时会抛出该方法。
因此,在您的情况下,最好提取当前Range的内容,将其追加到新节点中,然后在Range为以下的位置插入该新节点:
document.getElementById('target').addEventListener('mouseup', e => {
const sel = getSelection();
const range = sel.getRangeAt(0);
const highlighter = document.createElement('span');
highlighter.classList.add('highlight');
highlighter.append(range.extractContents());
range.insertNode(highlighter);
})
.highlight { color: red; }
<p id="target">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句