2013-03-05 242 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>