Javascript HTML格式的选定文本从范围选择返回空白
我有一个Javascript例程,由格式化为HTML的用户检索选择文本:Javascript HTML格式的选定文本从范围选择返回空白,javascript,Javascript,我有一个Javascript例程,由格式化为HTML的用户检索选择文本: function getHTMLOfSelection() { var range; if (document.selection && document.selection.createRange) { range = document.selection.createRange(); return range.htmlText; } els
function getHTMLOfSelection() {
var range;
if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
return range.htmlText;
}
else if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
range = selection.getRangeAt(0);
var clonedSelection = range.cloneContents();
var div = document.createElement('div');
div.appendChild(clonedSelection);
return div.innerHTML;
}
else {
return '';
}
}
else {
return '';
}
}
使用提琴,确保并首先选择引用的文本:
代码工作正常,但是,选择在每个
和
之后都包含一个\r\n
。
为什么要添加这些内容?添加到什么位置?这似乎是多余的,因为
和
标记已经包含了新行。根据OP的评论,如果您想返回HTML而不换行,您可以使用正则表达式全局替换回车(\n
)和换行(\r
)按空字符串排列的字符:
//apply this to remove line breaks from your strings, where str is the string
str = str.replace(/\n|\r/g, '');
//or directly in the return inside of your functions:
return range.htmlText.replace(/\n|\r/g, '');
return div.innerHTML.replace(/\n|\r/g, '');
这将删除所有换行符,请注意,如果选择文档的长部分,HTML将失去可读性
Oop,无所谓;你的小提琴很管用。我不知道你必须先选择文本。@JaredFarrish:因为http://jsfiddle.net/Y4BBq/13/
404s.@Rocket-Nevermind,愚蠢的JSFIDLE在链接上附加了我的用户名,我没有注意到。Fixed.Jackson,我想你的意思是将选择解释为包含空格,空格由浏览器中的HTML元素表示(虽然从技术上讲,那时它们是DOM元素)。对吗?你是说\r\n
-换行符-是“多余的”?所以您想在一行代码中读取所有返回的HTML?您知道\r\n
是Windows表示换行符的默认方式,并且您从中获得选择的文档确实有换行符,对吗?当插入文本区域时,\r\n
字符被正确地呈现为换行符,这意味着它将准确地显示您选择的文档。我看不出你有什么问题。