Decimal ignored when changing font size with JS

2019-09-06 04:20发布

问题:

I'm trying to add some text resize functionality using this code:

$('#text-resize a').click(function(){
    var currentValue = $('#page-body').css('fontSize');
    var currentSize = parseFloat(currentValue, 10);
    var fontUnit = currentValue.slice(-2);
    var newSize = currentSize;
    if ($(this).attr('rel') == 'decrease'){
        if (currentSize > 13){
            var newSize = currentSize / 1.2;
        }
    }
    else if ($(this).attr('rel') == 'increase'){
        if (currentSize < 19){
            var newSize = currentSize * 1.2;
        }
    }
    else {
        newSize = 1;
        fontUnit = 'em';
    }
    newSize += fontUnit;
    $('#page-body').css('fontSize', newSize);
    return false;
});

I know it's not the cleanest code, but my problem is that at some point (either getting or setting the font size for #page-body decimal points are being lost.

For example, I start with a value of 16px (from my CSS file) and when I increase it gets calculated to 19.2px. If I increase again, an alert of the currentValue (I have left out the alert) says it's 19px.

Can anyone tell me why decimal places are being ignored and how to prevent that?

If it helps, my starting CSS includes:

body { font-size: 16px; }
#page-body { font-size: 1em; }

Thanks

回答1:

A font size can only be a whole number of pixels, so when you set the font-size the browser casts the invalid font size to something it can use. The next time you get it, it's an integer number.

Since you're setting the font size on an element identified by ID, you should store the size in a variable and only set (never get) the element css font size.

For example, see http://jsfiddle.net/Qfzpb/



回答2:

Sub-pixel rendering is inconsistent between browsers.

Font size can be a <length>, and a <length> is a <number> (with or without a decimal point) immediately followed by a unit identifier (e.g., px, em, etc.). http://www.w3.org/TR/CSS21/fonts.html#font-size-props

CSS 3 says " UAs should support reasonably useful ranges and precisions. " Open-to-interpretation wording as 'reasonable' and 'useful': http://dev.w3.org/csswg/css3-values/#numeric-types



回答3:

$('#page-body').css('fontSize')

This may return different values(depending on the used browser).

Usually (in modern browsers) jQuery gets the value by using getComputedStyle() . The returned value here is the value used by the browser, not the value the style-property is set to. You may use this instead:

var currentValue = document.getElementById('page-body').style.fontSize
                      ||
                   $('#page-body').css('fontSize');

See the fiddle to determine the differences: http://jsfiddle.net/doktormolle/DMWhh/