问题描述
基本上我只需要从浏览器窗口复制该 HTML 并将其粘贴到 textarea 元素中的效果.
Basically I just need the effect of copying that HTML from browser window and pasting it in a textarea element.
例如我想要这个:
<p>Some</p>
<div>text<br />Some</div>
<div>text</div>
变成这样:
Some
text
Some
text
推荐答案
如果该 HTML 在您的网页中可见,您可以通过用户选择(或在 IE 中仅使用 TextRange
)来实现.这确实保留了换行符,即使不一定是前导和尾随空格.
If that HTML is visible within your web page, you could do it with the user selection (or just a TextRange
in IE). This does preserve line breaks, if not necessarily leading and trailing white space.
2012 年 12 月 10 日更新
然而,Selection
对象的 toString()
方法是 尚未标准化 并且在浏览器之间的工作不一致,因此这种方法基于不稳定的基础,我不推荐现在使用它.如果不接受,我会删除此答案.
However, the toString()
method of Selection
objects is not yet standardized and works inconsistently between browsers, so this approach is based on shaky ground and I don't recommend using it now. I would delete this answer if it weren't accepted.
代码:
function getInnerText(el) {
var sel, range, innerText = "";
if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") {
range = document.body.createTextRange();
range.moveToElementText(el);
innerText = range.text;
} else if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
sel = window.getSelection();
sel.selectAllChildren(el);
innerText = "" + sel;
sel.removeAllRanges();
}
return innerText;
}
这篇关于将 HTML 转换为纯文本同时保留换行符(使用 JavaScript)的最便捷方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!