2011-08-04 59 views
1

我設法將一個腳本,將增加使用按鈕或鏈接的網頁部分的字體大小。它在Moz/Chrome中工作,但堅持IE瀏覽器,理論上它應該不會在這些主流瀏覽器中遇到問題。但我堅持是否可以使用currentStyle從getElementsByName填充的變量中獲取fontSize;當然IE瀏覽器正在繪製空白。Javascript來增加/減少字體大小(外部CSS)

這裏是我的腳本:

function changeFontSize(element,step) 
{ 
    var styleProp = 'font-size'; 
    step = parseInt(step,10); 

    var x = document.getElementsByName(element); 

    for(i=0;i<x.length;i++) { 

     if (x[i].currentStyle) { 
      var y = parseInt(x[i].currentStyle[styleProp],10); 

     } else if (window.getComputedStyle) {   
      var y = parseInt(document.defaultView.getComputedStyle(x[i],null).getPropertyValue(styleProp),10); 

     } 

     x[i].style.fontSize = (y+step) + 'px'; 
    } 
} 

我用來拉了一起的3個站點是:

www.vijayjoshi.org

www.quirksmode.org

和(這不是垃圾郵件,這實際上很重要)//http://www.white-hat-web-design.co.uk/blog/controlling-font-size-with-javascript/

任何人都可以指出一個解決方案嗎?提前致謝!

回答

1

怎麼樣用下面的更新代碼:與修復和一些更好的命名了一些變量

function changeFontSize(element,step) 
{ 
function computeFontSizeUpdate(oE) 
{ 
//- init fSize with proper null value 
var fSize = null; 
//- retrieve fSize from style 
if (oE.currentStyle) { 
    fSize = parseInt(oE.currentStyle[styleProp], 10); 
} 
else if (window.getComputedStyle) { 
    var s = document.defaultView.getComputedStyle(oE,null); 
    fSize = (s) ? parseInt(s.getPropertyValue(styleProp),10) : NaN; 
} 

//- check fSize value based on return of parseInt function 
if(isNaN(fSize) == false && fSize != null) 
{ 
    fSize += nStep + 'px'; 
    if(oE.currentStyle) 
     oE.currentStyle.fontSize = fSize; 
    else 
     oE.style.fontSize = fSize; 
} 
}; 

var styleProp = 'font-size'; 
var nStep = parseInt(step, 10); 

//- ensure step value 
if(isNaN(nStep)) nStep = 0; 

//- get target elements 
var oElems = document.getElementsByName(element); 

if (oElems && oElems.length == 0) 
{ 
    var oE = document.getElementById(element); 
    if(oE) computeFontSizeUpdate(oE); 
} 
else 
{ 
    for(oE in oElems) 
    { 
    computeFontSizeUpdate(oE); 
    } 
} 

} 

我已經更新腳本。

此外,我很抱歉,因爲我現在在Mac上,我無法測試在IE提供的腳本...但從我記得應該做的伎倆。

使用一些JS控制檯,您可以直接直接將此頁

changeFontSize("nav-tags", 50); 

上執行,你會發現,在菜單欄中的標籤元素將得到受影響:)

希望這有助於

+0

這裏有一個錯誤: var s = document.defaultView.getComputedStyle(x [i],null);' 問題與x [i] var?看不到它應該是什麼。我試過oE,錯誤消息說「沒有這樣的接口支持」。 – Moniarde

+0

請檢查更新的代碼。謝謝:) –

+0

我認爲同樣的問題。這裏是我在Firebug中遇到的錯誤:'未捕獲的異常:[Exception ...「無法轉換JavaScript參數arg 0 [nsIDOMViewCSS.getComputedStyle]」'我認爲它在代碼的第12行。 – Moniarde