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

Deadly 提交于 2019-12-25 02:16:04

问题


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');
}

回答1:


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/




回答2:


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');
}


来源:https://stackoverflow.com/questions/8553060/changing-font-size-with-jquery-css-function-is-crashing-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!