Extracting text from a contentEditable div

后端 未结 6 1939
囚心锁ツ
囚心锁ツ 2020-12-02 09:36

I have a div set to contentEditable and styled with \"white-space:pre\" so it keeps things like linebreaks. In Safari, FF and IE, the div pretty mu

6条回答
  •  星月不相逢
    2020-12-02 10:19

    Unfortunately you do still have to handle this for the pre case individually per-browser (I don't condone browser detection in many cases, use feature detection...but in this case it's necessary), but luckily you can take care of them all pretty concisely, like this:

    var ce = $("
    ").html($("#edit").html());
    if($.browser.webkit) 
      ce.find("div").replaceWith(function() { return "\n" + this.innerHTML; });    
    if($.browser.msie) 
      ce.find("p").replaceWith(function() { return this.innerHTML  +  "
    "; }); if($.browser.mozilla || $.browser.opera ||$.browser.msie ) ce.find("br").replaceWith("\n"); var textWithWhiteSpaceIntact = ce.text();

    You can test it out here. IE in particular is a hassle because of the way is does   and new lines in text conversion, that's why it gets the
    treatment above to make it consistent, so it needs 2 passes to be handled correctly.

    In the above #edit is the ID of the contentEditable component, so just change that out, or make this a function, for example:

    function getContentEditableText(id) {
        var ce = $("
    ").html($("#" + id).html());
        if ($.browser.webkit)
          ce.find("div").replaceWith(function() { return "\n" + this.innerHTML; });
        if ($.browser.msie)
          ce.find("p").replaceWith(function() { return this.innerHTML + "
    "; }); if ($.browser.mozilla || $.browser.opera || $.browser.msie) ce.find("br").replaceWith("\n"); return ce.text(); }

    You can test that here. Or, since this is built on jQuery methods anyway, make it a plugin, like this:

    $.fn.getPreText = function () {
        var ce = $("
    ").html(this.html());
        if ($.browser.webkit)
          ce.find("div").replaceWith(function() { return "\n" + this.innerHTML; });
        if ($.browser.msie)
          ce.find("p").replaceWith(function() { return this.innerHTML + "
    "; }); if ($.browser.mozilla || $.browser.opera || $.browser.msie) ce.find("br").replaceWith("\n"); return ce.text(); };

    Then you can just call it with $("#edit").getPreText(), you can test that version here.

提交回复
热议问题