开发者

Conditionally adding a <br> to text within a <p> tag using jQuery

开发者 https://www.devze.com 2022-12-16 22:42 出处:网络
I have HTML code like this: <div id=\"paragraph\"> <pre> <p>First Line in the paragraph , this goes very long and very very long</p>

I have HTML code like this:

<div id="paragraph">
<pre>
<p>First Line in the paragraph , this goes very long and very very long</p>
<p>This line is of normal size
</pre>
</div>

Now, because of the first line, I get a scroll bar in my dialog box. I want to use jQuery and break the text inside the all <p> tag inside the "paragraph" div if it's greater than certain length during body load. So that it becomes some开发者_如何学Cthing like this:

<div id="paragraph">
<pre>
<p>First Line in the paragraph , this goes very long
<br/>
and very very long</p>
<p>This line is of normal size
</pre>
</div>

Is there a way to do this using jQuery?

Thanks! Pratik


You'll get a scroll bar using <pre> tag because it will not allow your paragraph tag to wrap. Use it without that tag.


You should loop through all <p> elements, get the length of their text, and then apply the line breaks.

$(document).ready(function() {
    $("p").each(function(i, item) {
        if($(item).text().length > 10) $(item).text(breakLongLine($(item).text()));
    });

    function breakLongLine(text) {
        // add </br>
    }
});


I'm not sure about doing this with jquery, but using the method here with css you can have the text auto wrap

http://www.longren.org/2006/09/27/wrapping-text-inside-pre-tags/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号