如何动态附加< span>标签放入< p>的特定位置标签? [英] How do I dynamically append a <span> tag into a specific location of the <p> tag?

查看:85
本文介绍了如何动态附加< span>标签放入< p>的特定位置标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从本质上讲,我正在尝试实现一项功能,该功能可以在选中时突出显示某些文本。严格来说,这仅适用于Google Chrome浏览器。

In essence, I'm trying to implement a feature which highlights certain text when selected. This is strictly for the Google Chrome browser.

例如:
选择之前:

For example: Before selection:

<html>
    <body>
        <p>sample text</p>
    </body>
</html>

从示例文本中选择文本后:

After selecting "text" from "sample text":

<html>
    <body>
        <p>sample <span class="state-highlighted">text</span> </p>
    </body>
</html>

JavaScript:

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.

  });
});

我可以从一个简单的问题开始:
如何插入

I could start with a simpler question: How do I insert a span element into a paragragh element, let's say on click?

推荐答案

有一个 Range.surroundContents 方法
因此,在您的情况下,最好提取当前范围的内容,将其附加到新节点中,然后插入该新节点,其范围为:

There is a Range.surroundContents method that would come handy here, but it will throw when selecting only part of an element.
So in your case it might be better to extract the content of the current Range, append it in your new node, and then insert that new node where the Range is:

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>

这篇关于如何动态附加&lt; span&gt;标签放入&lt; p&gt;的特定位置标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆