javascript - 如何动态地将 <span> 标签附加到 <p> 标签的特定位置?

标签 javascript html dom google-chrome-extension

本质上,我正在尝试实现一个在选择时突出显示某些文本的功能。这仅适用于 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/

相关文章:

javascript - 如何用 React 删除一个列表项(函数组件)

javascript - 通过传递 jquery 变量切换按钮

google-chrome - 将dom内容导出为html文件chrome

javascript - Firefox 将注释文本保存在 style 元素内的 textContent 中

javascript - Android 警报 "Don' t 再次显示“Web View 中的复选框

javascript - 仅增加选定边缘的宽度 (cytoscape.js)

Javascript 的 object.onClick 运行函数而不是设置 onClick,如何防止这种情况发生并只执行函数 onClick?

javascript - 获取不在特定 div 中的所有表单输入

html - 如何对齐 <td rowspan ="value"> 值垂直居中?

javascript - 使用 Dom 对象将单词包装在所有相同的选择器中