2013-03-05 234 views
0

我正在尝试获取我的浏览器用于显示警报,提示等的字体大小和fontfamily。所以我这样做:
alert(document.body.style.fontFamily);但它显示出一个空白的警报。我哪里错了?Javascript为浏览器获取默认字体大小

回答

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

1

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

+0

其实他们是通过浏览器中呈现,每个浏览器呈现他们以自己的风格。 – kennebec 2013-03-05 17:26:57

1

好吧,我同意Kolink上面说的,但有什么事,你也可以试试:

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

与上面的代码,一旦你打开你的FF和更改比例设置,您可能会看到输出也改变了。玩得开心:)

enter image description here

1

不能直接测量一个对话框,但你可以用一个关键字一个元素的字体设置为浏览器的系统字体,并检查该元素。

您可以动态创建样式隐藏元素=“FONT:消息盒子”,这个例子使用了页面的现有的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>