简体   繁体   中英

Changing font-size with jQuery css() function is crashing Chrome

So I have this bit of code that works perfectly in FF and IE8, but it's crashing Chrome:

while($('#movie-info .vote').height()>30) {
    $size = $('#movie-info .vote').css('font-size').replace('px','');
    $('#movie-info .vote').css('font-size',($size-0.5)+'px');
}

I stumbled upon this old question looking for a different issue, but I think I can shed some light on the issue, especially considering the "works with -1 instead of -0.5" thing.

Chrome and other WebKit-based browsers handle unit rounding differently than Firefox and IE. While Firefox does its best to render and report fractional pixel sizes and IE renders rounded sizes but continues to report exactly what you specified, WebKit rounds the rendered value AND reports the rounded value when you ask for it back.

Let's say the size starts at 14px. When you run this code:

// $size = 14
$size = $('#movie-info .vote').css('font-size').replace('px','');
// font-size: 13.5px
$('#movie-info .vote').css('font-size',($size-0.5)+'px');

Chrome rounds off your size change and the font size is still 14px. So, the loop will never stop because $size never decreases.

A simple solution would be to declare $size once instead of asking Chrome what it is:

// Don't forget to declare with `var` to give $size local scope!
// Otherwise it is declared in global scope which could lead to
// weird bugs or lost performance.
var $size = $('#movie-info .vote').css('font-size').replace('px','');
while ($('#movie-info .vote').height() > 30) {
    $size = $size - 0.5;
    $('#movie-info .vote').css('font-size', $size + 'px');
}

I guess that happens because chrome doesn't allow font-size to go under a certain limit, but when font-size reaches the limit, height is still > 30..?

I think you should avoid the for loop, and instead recalculate optimum font size at once, depending on '#movie-info .vote' height..

UPDATE

To have one-line rows, with hidden continuation, use something like this:

#movie-info .vote {
    line-height: 1.5em;
    height: 1.5em;
    overflow: hidden;
    white-space: nowrap;
}

Try this out here: http://jsfiddle.net/fvcHd/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM