使用JS更改字体大小时忽略小数 [英] Decimal ignored when changing font size with JS

查看:270
本文介绍了使用JS更改字体大小时忽略小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用此代码添加一些文本调整大小功能:

  $('#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')==' ){
if(currentSize< 19){
var newSize = currentSize * 1.2;
}
}
else {
newSize = 1;
fontUnit ='em';
}
newSize + = fontUnit;
$('#page-body')。css('fontSize',newSize);
return false;
});

我知道这不是最干净的代码,但我的问题是, #page-body 小数点的字体大小会丢失。



例如, 16px(从我的CSS文件),当我增加它计算到19.2px。如果我再次增加,currentValue的警报(我已经忽略了警报)说它是19px。


$



如果有帮助,我的起始CSS包括:

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



感谢

解决方案

一个字体大小只能是一个整数的像素,所以当你设置字体大小的浏览器转换无效的字体大小到可以使用的东西下一次你得到它是一个整数。



由于你在由ID标识的元素上设置字体大小,你应该将大小存储在变量中,并且只设置(永远不会)元素css字体大小。



例如,请参见 http://jsfiddle.net/Qfzpb/


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

解决方案

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/

这篇关于使用JS更改字体大小时忽略小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆