如何动态地将标签添加到 标签的特定位置?

问题描述 投票:1回答:1

本质上,我正在尝试实现一项功能,该功能在选中时突出显示某些文本。这仅适用于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元素中?

javascript html dom google-chrome-extension
1个回答
0
投票

在鼠标悬停时,调用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相应。

© www.soinside.com 2019 - 2024. All rights reserved.