Javascript获取浏览器的默认字体大小

时间:2013-03-05 16:02:05

标签: javascript browser fonts

我正在尝试使用我的浏览器用来显示警报,提示等的fontsize和fontfamily。所以我这样做:
警报(document.body.style.fontFamily);但它显示了一个空白警报。我哪里错了?

4 个答案:

答案 0 :(得分:3)

嗯,我同意Kolink上面所说的内容,但您可能也想尝试一下:

<body id="body">
<script>
var theCSSprop = window.getComputedStyle(document.body,null).getPropertyValue("font-family");
console.log(theCSSprop); // output: serif
</script>
</body>

使用上面的代码,一旦打开FF并更改比例设置,您可能会看到输出也被更改。玩得开心:))

enter image description here

答案 1 :(得分:1)

警报(确认,提示)框等控件由操作系统而不是浏览器呈现。你无法控制它。

答案 2 :(得分:1)

您无法直接测量对话框,但可以使用关键字将元素的字体设置为浏览器系统字体并检查该元素。

您可以使用style =“font:message-box”动态创建隐藏元素,此示例使用页面的现有css:

<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Small Page</title>
<style>
.message{border:2px black ridge;font:message-box}
</style>

</head>
<body>

<div class="message">

<p><strong>"Here's another fine mess you've gotten us in."- 
        <em> Oliver Hardy</em></strong></p>
</div>

<script>
onload= function(){
    var who= document.getElementsByTagName('div')[0],props;
    if(window.getComputedStyle){
        who= getComputedStyle(who, ''),
        props= ['font-family', 'font-size', 'font-weight', 
        'line-height'].map(function(itm){
            return itm+': '+who.getPropertyValue(itm);
        });     
    }
    else if(who.currentStyle){//IE<9
        who= who.currentStyle;
        props= ['fontFamily', 'fontSize', 'fontWeight',
        'lineHeight'].map(function(itm){
            return itm+': '+ who[itm];
        });
    }
    alert(props.join('\n'));
}

if(!Array.prototype.map){//IE<9
    Array.prototype.map= function(fun, scope){
        var T= this, L= T.length, A= Array(L), i= 0;
        if(typeof fun== 'function'){
            while(i<L){
                if(i in T){
                    A[i]= fun.call(scope, T[i], i, T);
                }
                ++i;
            }
            return A;
        }
    }
}

</script>
</body>
</html>

答案 3 :(得分:0)

SomeElement.style.SomeStyle仅选取元素的style属性中定义的样式。因此,如果您没有专门的<body style="font-family:blah">,那么您将没有结果。

可以使用getComputedStyle从样式表中获取样式,但这需要旧版IE中的垫片:

window.getComputedStyle = window.getComputedStyle || function(e) {return e.currentStyle;};

此外,这并不是你真正想要的。

理论上,您可以在网页上获取默认的文字样式,如下所示:

window.getComputedStyle(document.createElement('div')).fontFamily;

但是,这不一定(通常不是)与警报和提示中使用的字体相同。这些是由操作系统呈现而不是浏览器,因此很遗憾无法知道用户是否更改了其设置中的字体。如果有帮助,我相信此类框的默认值为Arial 10pt