Extracting text from a contentEditable div

后端 未结 6 1935
囚心锁ツ
囚心锁ツ 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:24

    here's a solution (using underscore and jquery) that seems to work in iOS Safari (iOS 7 and 8), Safari 8, Chrome 43, and Firefox 36 in OS X, and IE6-11 on Windows:

    _.reduce($editable.contents(), function(text, node) {
        return text + (node.nodeValue || '\n' +
            (_.isString(node.textContent) ? node.textContent : node.innerHTML));
    }, '')
    

    see test page here: http://brokendisk.com/code/contenteditable.html

    although I think the real answer is that if you're not interested in the markup provided by the browser, you shouldn't be using the contenteditable attribute - a textarea would be the proper tool for the job.

提交回复
热议问题