在段落标签内为所选文本插入HTML标签

时间:2019-01-09 06:39:26

标签: javascript html ckeditor

我正在尝试为段落标记中的选定元素添加新元素。 HTML代码段如下:

 <div class="parent-bodytext">
     <p>Hello</p>
     <p>This one is</p>
     <p>Sample Text</p>
 </div>

因此,在上面的代码段中,我从第二个P标签中选择了“一个”字,并使用任何事件试图将元素添加到所选文本中,以便输出如下所示:

 <div class="parent-bodytext">
     <p>Hello</p>
     <p>This <strong>one</strong> is</p>
     <p>Sample Text</p>
 </div>

那么如何为选定的所选文本添加这个新创建的“强”元素?

3 个答案:

答案 0 :(得分:2)

您可能要为此目的使用window.getSelection

const wrapper = document.getElementsByClassName('parent-bodytext')[0];

wrapper.addEventListener('mouseout', event => {
   const selection = window.getSelection();
   if (selection.rangeCount) {
       const replacement = document.createElement('strong');
       replacement.textContent = selection.toString();
       const range = selection.getRangeAt(0);
       range.deleteContents();
       range.insertNode(replacement);
   }
});
 <div class="parent-bodytext">
 <p>Hello</p>
 <p>This one is</p>
 <p>Sample Text</p>
 </div>

答案 1 :(得分:2)

您想要这样的东西吗?

window.onload = () => {
  function getSelectionParentElement() {
    var parentEl = null,
      sel;
    if (window.getSelection) {
      sel = window.getSelection();
      if (sel.rangeCount) {
        parentEl = sel.getRangeAt(0).commonAncestorContainer;
        if (parentEl.nodeType != 1) {
          parentEl = parentEl.parentNode;
        }
      }
    } else if ((sel = document.selection) && sel.type != "Control") {
      parentEl = sel.createRange().parentElement();
    }
    return parentEl;
  }

  function getSelectedText() {
    var text = "";
    if (typeof window.getSelection != "undefined") {
      text = window.getSelection().toString();
    } else if (
      typeof document.selection != "undefined" &&
      document.selection.type == "Text"
    ) {
      text = document.selection.createRange().text;
    }
    return text;
  }
  
  const makeBold = (selectStart, selectEnd, length, text)=>{
    let replacedText = `<strong>${text.substr(selectStart, length)}</strong>`;
    let textHalfA = text.substr(0, selectStart);
    let textHalfB = text.substr(selectEnd, text.length - 1);
    return textHalfA + replacedText + textHalfB;
  };
  
  function handleMouseUp() {
    // the selected text
    const text = getSelectedText();
    // the length of the selected content
    const selectedTextLength = text.length;
    // the parent of the selected content
    let parent = getSelectionParentElement();
    // the entire content of the parent
    let parentText = parent.innerHTML;
    // where the user's selection starts
    let selectStart = window.getSelection().getRangeAt(0).startOffset;
    // where the user's selection ends
    let selectEnd = window.getSelection().getRangeAt(0).endOffset;
    if (parent) {
      parent.innerHTML = makeBold(selectStart, selectEnd, selectedTextLength, parentText);
    }
  }

  document.onmouseup = handleMouseUp;
  document.onkeyup = handleMouseUp;
};
<p>I am a sentence.</p>

来源将是thisthis

另外,这是pen:)


编辑:代码已更新。现在应该正确完成对所选内容的修改。虽然,我不知道如何处理已修改元素的第二次修改。(我会尽快再次更新。除非OP有一个想法;))

答案 2 :(得分:0)

编辑:已删除jQuery依赖 您可以使用CSS来实现。 首先,您需要使用跨度分隔每个单词。 然后在事件发生的范围内添加强类

window.onload = function () {
  document.getElementsByClassName("parent-bodytext")[0].onclick = function(e) {
    var tgt = e.target;
    if (tgt && tgt.nodeName === 'SPAN') {
      tgt.classList.add('strong');
    }
  };
};
.strong{
  font-weight: bold;
}
<div class="parent-bodytext">
     <p><span>Hello</span></p>
     <p><span>This</span> <span>one</span> <span>is</span></p>
     <p><span>Sample</span> <span>Text</span></p>
 </div>