How to check a string is longer than the container div's width in Jquery?
E.g:
.container{ width:200px; height:16px;overflow:hidden;font-size:13px; }
<div class="container">
I want to know this sentence's width is bigger than my container div's width
</div>
and if the string inside the container
is much longer
, is there a way I can animate the string from开发者_如何学JAVA begin to the end and loop again and again
. But if shorter,just stay!!
[update]
With Don's way
, the inner element with string's width
aways equal the width of container
and string was wrapped.So,how can I do to set the inner element's width
to be the string's actual length
!?
Thank you very much!
you could solve that with a ruler: add to your site that <div>
<div id="ruler" style="display: none">
I want to know this sentence's width is bigger than my container div's width
</div>
Now you can get the length of the string and compare it to the length of your .container
if ($("#ruler").width() > $(".container").width()) {
//what ever you want to do if the string is to long
}
I think you should put your string in an inner element (such as div
, p
, h1
, ...) and then compare its width to the container's one.
There is not really a good way to figure out if the text exceeds the div
's size, although doing some googling does bring us to another stackoverflow question and answer.
You could take that and use the jQuery plugin jQscroller to scroll the text if it exceeds the div's size.
A simple way if you don't care for the exact width would be to wrap the text in a span element as it will take the size of the text. You can then use $('span').outerWidth()
and compare it to the $('#container').width()
if they're the same you can assume the text wrapped around and should be scrolled. If the span
's width is smaller it should just stay still. (This method might be inaccurate by a few pixels)
精彩评论