将长单个单词拆分为多行而不会破坏链接或html标记

时间:2012-07-11 18:42:07

标签: jquery html

我在$(document).ready(function(){...}的页面上有以下行,它在ASP.NET中完成

$("#standard-styling").html($("#standard-styling").text().replace(/([^\s-]{5})(?=[^\s-])/g, '$1­'));

HTML:

<div id="standard-styling" class="description">
    <% Response.Write(Model.Description); %>
</div>

如果浏览器认为有必要,可以通过添加-<br>将长单词拆分为多行,并且如果不是(http://www.quirksmode.org/oddsandends/wbr.html)则忽略它。但是,如果描述包含链接,则链接不会显示为超链接。此外,如果有换行符<br />或其他标记,它们也可能会被破坏并被忽略。最后,它导致像&lt;br /&gt;这样的编码字符出现问题。然后它被视为<br />,并在那里插入换行符。

有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用css:

#standard-styling {
   word-wrap: break-word;
}

或者使用jQuery:

$("#standard-styling").css('word-wrap', 'break-word');


UPD:

jQuery示例:http://jsbin.com/ojoges/1/

CSS示例:http://jsbin.com/ojoges/