【问题标题】:Select a text, put it in bold and save the position of the bold tags to surround these same texts later选择一个文本,把它加粗,然后保存粗体标签的位置,以便以后围绕这些相同的文本
【发布时间】:2019-06-16 01:57:41
【问题描述】:

我编辑了我的问题,因为它没有得到足够的解释

我的目标是让用户选择特定 div 中的一些文本,使这些文本变为粗体并保存这些选择的边界,以便以后检索它们。这样,我们可以想象(例如)当用户稍后返回此页面并加载此 div 时,他的粗体文本就在这里。

这就是为什么我需要保存一些数据来检索标签的“位置”以环绕选定的文本。但我不知道具体要保存什么,也不知道如何保存。

这里是场景。假设我们在文档的某处有这个 div:

<div id="unique">
  <p>My text is awesome !</p>
  <div>
    <div>
      Here is an other text interesting too.
    </div>
  </div>
 </div>

用户做了两个选择,所以我基本使用

var selection = window.getSelection()

我有额外的代码来限制选择等等......但这并不重要。最后,我检索了一个基于此代码的 Range 对象

var range = selection.getRangeAt(0)

为了将文本加粗,我使用:

range.surroundContents(document.createElement("b"));

而且它的工作原理是,每次用户选择某些东西时,粗体标签都会像这样插入到 DOM 中:

<div id="unique">
  <p>My <b>text is awesome</b> !</p>
  <div>
    <div>
      Here is <b>an other text</b> interesting too.
    </div>
  </div>
 </div>

所以现在我的问题是:我如何才能“保存”粗体标签相对于 id 为“唯一”的 div 的确切“位置”,以便稍后加载它们(加载意味着这里再次用标签包围)。更准确地说,我的问题是我需要保存哪些数据?

我尝试存储 Range 对象,但它们正在演变,因为每次我用粗体标签包围文本时,DOM 都会受到影响,Range 对象也会受到影响。

在像这样的函数的最后,我希望能够将文本放回粗体

loadBolds() {
  //boldRanges is an array containing the ranges of the selections

  boldRanges.forEach((range) => {
    range.surroundContents(document.createElement("bold"))
  });
}

我希望现在清楚了!

谢谢

【问题讨论】:

  • 你在这里尝试了什么?请张贴。

标签: javascript dom range


【解决方案1】:

您可以使用一组函数来处理节点,以某种有组织的方式保存结果并保存。

function hasBold(n) {
  return !!n.getElementsByTagName && !!n.getElementsByTagName('b').length;
}

function boldText(n) {
  return (n.nodeName == "B") ? n.textContent : "";
}

function boldCount(n) {
  return !!n.getElementsByTagName ? n.getElementsByTagName('b').length : 0;
}

function indexInSiblings(n) {
  var i = 0;
  while ((n = n.previousSibling) != null)
    i++;
  return i;
}

function checkNode(n, t = "B") {
  return {
    is: n.nodeName == "B",
    name: n.nodeName,
    text: boldText(n),
    has: hasBold(n),
    count: boldCount(n)
  };
}
const container = document.getElementById('unique');
let c = checkNode(container);
console.log(c);
var nodeList = container.childNodes;//5
var nodeC = container.children;//2
console.log("nodeList,nodeC:",nodeList.length,nodeC.length);
console.log("nodeName:1,1", nodeList[1].childNodes[1].nodeName);
console.log("nodeName:0", nodeList[0].nodeName);

let nodeN = 1;
let me = nodeList[nodeN].childNodes[1];
console.log("nodeList:" + nodeN, me.nodeName, checkNode(me));
<div id="unique">
  <p>My <b>text is awesome</b> !</p>
  <div>
    <div>
      Here is <b>an other text</b> interesting too.
    </div>
  </div>
</div>

【讨论】:

    【解决方案2】:

    我在那里发现了一个类似的问题,我想它会解决我的问题

    Save selection text and show it later in html and javascript

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2014-09-04
      • 1970-01-01
      相关资源
      最近更新 更多