Joe*_*ong 107 html javascript jquery
我希望能够说出来
$(someElem).text('this\n has\n newlines);
Run Code Online (Sandbox Code Playgroud)
并在浏览器中使用换行符进行渲染.我发现的唯一解决方法是在someElem上将css属性'white-space'设置为'pre'.这几乎可以工作,但是我在someElem的文本和顶部之间有一个令人讨厌的大填充,即使我将填充设置为0.有没有办法摆脱这个?
cle*_*ong 121
这是2015年.此问题的正确答案是使用CSS white-space: pre-line
或white-space: pre-wrap
.干净优雅.支持该对的IE的最低版本是8.
https://css-tricks.com/almanac/properties/w/whitespace/
PS 直到CSS3变得普遍,您可能需要手动修剪初始和/或尾随空格.
Jos*_*ior 54
如果将jQuery对象存储在变量中,则可以执行以下操作:
var obj = $("#example").text('this\n has\n newlines');
obj.html(obj.html().replace(/\n/g,'<br/>'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
Run Code Online (Sandbox Code Playgroud)
如果您愿意,还可以使用简单的调用创建一个函数来完成此操作,就像jQuery.text()一样:
$.fn.multiline = function(text){
this.text(text);
this.html(this.html().replace(/\n/g,'<br/>'));
return this;
}
// Now you can do this:
$("#example").multiline('this\n has\n newlines');
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="example"></p>
Run Code Online (Sandbox Code Playgroud)
Pet*_*rch 37
这是我使用的:
function htmlForTextWithEmbeddedNewlines(text) {
var htmls = [];
var lines = text.split(/\n/);
// The temporary <div/> is to perform HTML entity encoding reliably.
//
// document.createElement() is *much* faster than jQuery('<div></div>')
// http://stackoverflow.com/questions/268490/
//
// You don't need jQuery but then you need to struggle with browser
// differences in innerText/textContent yourself
var tmpDiv = jQuery(document.createElement('div'));
for (var i = 0 ; i < lines.length ; i++) {
htmls.push(tmpDiv.text(lines[i]).html());
}
return htmls.join("<br>");
}
jQuery('#div').html(htmlForTextWithEmbeddedNewlines("hello\nworld"));
Run Code Online (Sandbox Code Playgroud)
kar*_*m79 20
或者,尝试使用.html
然后用标签包装<pre>
:
$(someElem).html('this\n has\n newlines').wrap('<pre />');
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 12
您可以使用 html
替代text
和取代的每次出现\n
用<br>
.你必须正确地逃避你的文字.
x = x.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/\n/g, '<br>');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
136310 次 |
最近记录: |