本质上,我正在尝试实现一个在选择时突出显示某些文本的功能。这仅适用于 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 元素中,比如说单击时?
最佳答案
鼠标松开时,调用 window.getSelection()
获得 Selection目的。您可以检查它以查找 <p>
内所选内容的开始和结束文本。 。然后替换<p>
的 HTML 用 <span class="highlighted">
包围该文本部分:
const p = document.body.querySelector('p');
const origContent = p.textContent;
p.addEventListener('mousedown', () => {
p.textContent = origContent;
});
p.addEventListener('mouseup', (e) => {
const selection = window.getSelection();
if (!selection) {
return;
}
const range = selection.getRangeAt(0);
// If user starts highlighting on the right, and drags mouse to the left,
// endOffset will be smaller than startOffset:
const startIndex = Math.min(range.startOffset, range.endOffset);
const { length } = String(selection);
const endIndex = startIndex + length;
p.textContent = p.textContent;
p.innerHTML = (
p.textContent.slice(0, startIndex) +
'<span class="highlighted">' +
selection +
'</span>' +
p.textContent.slice(endIndex)
);
});
.highlighted {
background-color: orange;
}
<p>sample text sample text sample text sample text sample text sample text sample text sample text sample text</p>
如果用户可能一次选择文本的多个部分,并且您想要突出显示两个不连续的文本片段,则可以迭代 0 到 selection.rangeCount
的范围。并对原始上下文进行切片以相应地创建新的 HTML。
关于javascript - 如何动态地将 <span> 标签附加到 <p> 标签的特定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59606037/