通过javascript从contenteditable div获取文本内容

问题描述 投票:0回答:10

我想通过javascript从contentEditable div检索文本内容。这样做有哪些选择?我尝试过innerHTML,但它不起作用。

javascript html
10个回答
60
投票

为什么不使用 textContent 来实现此目的:

var contenteditable = document.querySelector('[contenteditable]'),
    text = contenteditable.textContent;

http://jsfiddle.net/E4W8y/1/


33
投票

不幸的是,我发现

innerText
是在 contenteditable dom 节点中保留换行符的唯一方法。我正在做的(目前仅在 Chrome 中测试)是这样的:

 var innerText = editableDiv.innerText  // using innerText here because it preserves newlines
 if(innerText[innerText.length-1] === '\n') 
     innerText = innerText.slice(0,-1)             // get rid of weird extra newline
 return innerText

7
投票

lblMailContent
是可编辑字段的id。

var details= document.getElementById("lblMailContent").innerHTML;

将此代码放入

clientClick
。这对我来说效果很好。


6
投票

使用 jQuery 并执行

var content = $('#my-contenteditable-div').html();

另请查找这些链接:

http://west-wind.com/Weblog/posts/778165.aspx

从 contentEditable div 中提取文本


3
投票

我这样解决了,因为我需要html输入:

message = $('<div>').html(
   $('#area').html()
   .replace(/<(div|p|br)[^<]*?>/g, '&lt;br /&gt;')
   .replace(/<([(i|a|b|u)^>]+)>(.*?)<\/\1>/gim,
      function(v) { return '' + escape(v) + ''; })
).text();

允许标签 A、B、I、U 并用 BR 替换 Div 和 Ps


2
投票

使用这个:

function textFromDiv(selector) {
  const element = document.querySelector(selector);
  const text = element.html().replace(/<div>/g,"\n").replace(/<\/div>/g,"").replace(/<br>/g,"\n");
  return text;
}```

2
投票

普通 JS 解决方案

html:

<div 
  contenteditable="true"
  onkeyup="myFunction(this, event)"
></div>

js:

function myFunction(self, event){
  console.log(self.innerText) 
  console.log(event)
} 

1
投票

使用文本内容,大多数情况下工作正常 工作示例:

jsfiddle
(在 Safari 中验证)


1
投票

这是我的看法...

input = document.getElementsByTagName("div")[0];

input.onkeyup = function(){
    text = "";
    for(i=0; i<input.childNodes.length; i++){
        text += input.childNodes[i].textContent + "\n";
    }
    text = text.trim();
    console.log(text);
}

0
投票

你可以用这个

document.querySelector("div").innerText.trim()
© www.soinside.com 2019 - 2024. All rights reserved.