2012-05-26 38 views
2

我試圖將嵌入樣式添加到具有特定計算樣式屬性的頁面中的元素。Javascript:爲具有特定計算樣式屬性的頁面中的元素添加嵌入樣式

例如:

<head> 
    <style> 
     p.mim { 
      cursor:pointer; 
     } 

     a.fif { 
      cursor:pointer; 
     } 

    </style> 
</head> 
<body> 
    <p class="mim">prova</p> 
    <a class="fif">prova</a> 
</body> 

我想補充一個內嵌式的「光標:等待」到了每一個元素「光標:指針」設定在計算樣式:

<body> 
    <p class="mim" style="cursor:wait;">prova</p> 
    <a class="fif" style="cursor:wait;">prova</a> 
</body> 

這是我嘗試過的:

var elms = document.getElementsByTagName("*"); 
for (var j = 0; j < elms.length; j++) { 

    var crs = getComputedStyle(elm, null).getPropertyCSSValue('cursor') || ""; 
    crs = crs.replace(/\s/g, "").toLowerCase(); 

    switch (crs) { 
     case "pointer": 
     case "Pointer": 
     case "POINTER": 
      elm.style.cursor = "wait"; 
      break; 
    } 
}); 
+0

是否有某種原因讓'});'最後? –

回答

1

您的代碼由於多種原因而是多餘的,而其他人則不完整。

首先,getComptedStyle在早期版本的IE中不存在。他們改爲使用currentStyle屬性。值得慶幸的是荒謬容易墊片這樣的:

if(typeof getComputedStyle == "undefined") getComputedStyle = function(elem) {return elem.currentStyle;}; 

現在,一個已經解決,除去null的說法,因爲它是完全多餘的。其實,我甚至不知道getComputedStyle第二個參數,但那只是我。

接下來,您可以通過獲取.cursor(或['cursor'])而不是那個.getPropertyCSSValue調用(我再也沒有聽說過...)來獲得遊標屬性。您還可以刪除|| "",因爲如果尚未設置cursor屬性,getComputedStyle將返回空字符串。

您不需要修剪空格,但切換爲小寫似乎是一個好主意,只是爲了安全起見。

...但是,緊接在toLowerCase()之後,您檢查了三個不同的詞的大寫字母嗎?真?

此外,你從來沒有定義elm(這是你的實際問題所在),你應該緩存值elms.length

最後的代碼應該是這樣的:

if(typeof getComputedStyle == "undefined") getComputedStyle = function(elem) {return elem.currentStyle;}; 
var elms = document.getElementsByTagName("*"), l = elms.length, i; 
for(i=0; i<l; i++) { 
    if(getComputedStyle(elms[i]).cursor.toLowerCase() === "pointer") { 
     elms[i].style.cursor = "wait"; 
    } 
} 

如果你希望能夠撤消這一點,你需要通過它來存儲你修改的元素,循環的陣列和刪除樣式(.style.cursor = "";)。

相關問題