2

我正在尝试获取我的浏览器用来显示警报、提示等的字体大小和字体系列。所以我这样做了:
alert(document.body.style.fontFamily); 但它向我显示了一个空白警报。我哪里错了?

4

4 回答 4

5

好吧,我同意 Kolink 上面所说的,但您可能还想尝试一下:

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

使用上面的代码,打开 FF 并更改 Proportional 设置后,您可能会看到输出也发生了变化。玩得开心 :)

在此处输入图像描述

于 2013-03-05T16:38:15.090 回答
1

诸如警报(确认、提示)框之类的控件由操作系统呈现,而不是由浏览器呈现。你无法控制这一点。

于 2013-03-05T16:03:27.763 回答
1

SomeElement.style.SomeStylestyle只选择元素属性中定义的样式。因此,如果您没有特别拥有,<body style="font-family:blah">那么您将没有结果。

可以使用 来从样式表中获取样式getComputedStyle,但这需要在旧版 IE 中使用 shim:

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

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

理论上,您可以像这样获得网页上的默认文本样式:

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

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

于 2013-03-05T16:08:40.937 回答
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>
于 2013-03-05T17:21:43.353 回答