【问题标题】:extend or expand element range contents?扩展或扩展元素范围内容?
【发布时间】:2017-09-26 22:26:02
【问题描述】:

是否可以扩展元素的内容?假设我们有文本“hello world of javascript”,但目前标签中只包含“hello”。我们如何扩展范围,让 hello 和 world 现在都在 span 标记内,同时不理会“of javascript”?

如:

<p><span class="bold">hello</span> world of javascript </p>

变成:

<p><span class="bold">hello world</span> of javascript </p>

【问题讨论】:

  • 你试过什么?请编辑您的问题以包含您尝试过的代码,以便我们帮助您修复它。

标签: javascript jquery


【解决方案1】:
// Get the plain text that's into the <p> tag (i.e hello world) and put it 
// as the inner text of span
$('span').html($('p').text());

// Clear the plain text nodes of <p> tag
$("p").contents().filter(function(){ 
  return this.nodeType == 3; 
})[0].nodeValue = "";

【讨论】:

  • 但它还需要处理一个更复杂的示例,其中包含长段文本。它应该能够将标签从字面上扩展到一个或多个单词,也可以将其收回
【解决方案2】:

这可以通过使用Ranges 来完成。

通过在文本节点上设置范围的开始和结束,可以选择文本的特定部分。然后,可以提取范围内的文本并将其添加到您正在扩展的节点中。文本节点可以通过规范化节点重新连接在一起。

const bold = document.querySelector(".bold"),
  container = document.querySelector("p"),
  range = document.createRange();
  
// selects the " world" from the paragraph
range.setStart(container.childNodes[1], 0);
range.setEnd(container.childNodes[1], 6);

// extracts the text from the range
const fragment = range.extractContents();

// move the text into the span
bold.appendChild(fragment);
bold.normalize();
.bold {
  font-weight: bold;
}
&lt;p&gt;&lt;span class="bold"&gt;hello&lt;/span&gt; world of javascript &lt;/p&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多