从contenteditable div剥离HTML格式,但保留粘贴时的换行符吗?

问题描述 投票:5回答:1

我目前有一个内容可编辑的div,我将其用作编辑器,但我希望在粘贴时剥离html(不包括<br>标签)。

目前,我有另一个div <div class="hiddendiv common editor"></div>,该div收集添加到contenteditable div的所有文本和数据,以便确定内容可编辑div的高度。

我很困惑,不确定如何去做。

我的问题是:如何在使用jQuery粘贴时在光标插入符处插入文本时,如何去除html格式(不包括<br>标签?

HTML:

<div contenteditable='true' id="textarea" class="editor plain-box large-box textarea text common text-content-input quicksand color-dark-grey" data-text="Start typing..."></div>

<div class="hiddendiv common editor"></div> 

jQuery

function pasteHtmlAtCaret(html) {
  var sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      var el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment(), node, lastNode;
      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }
      range.insertNode(frag);

      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if (document.selection && document.selection.type != "Control") {
    document.selection.createRange().pasteHTML(html);
  }
}

$('#textarea').on("paste", function() {
    var textarea = $('#textarea').html();
    var hidden_div = $('.hiddendiv').html(textarea);
    var plain_text = hidden_div.text();
    $('#textarea').pasteHtmlAtCaret(plain_text);
});

var txt = $('#textarea'),
    hiddenDiv = $(document.createElement('div')),
    content = null;

txt.addClass('txtstuff');
hiddenDiv.addClass('hiddendiv common editor');

$('body').append(hiddenDiv);

txt.on('keyup input propertychange', function () {

    content = $(this).html();

    content = content.replace(/\n/g, '<br>');
    hiddenDiv.html(content + '<br>');

    $(this).css('height', hiddenDiv.height());

});
javascript jquery html contenteditable
1个回答
0
投票

这可能是您要寻找的:

© www.soinside.com 2019 - 2024. All rights reserved.