2012-03-12 67 views
0

我已經搜索過並且爲此搜索了一些關於如何閱讀CSS propeties但非允許讀取僞類屬性的許多答案。如何在javascript中讀取Psuedo類的CSS屬性

我已經使用了以下內容,以便我可以在多種產品上輕鬆地重用某些頁面(固件/配置上傳)。

.productname:before 
{ 
    content: "My Shiny New Product"; 
} 

然後

<span class="productname" /> 
在html

插入正確的名稱。

當前向服務器發送固件更新時,沒有在客戶端瀏覽器上進行檢查,並且服務器返回[請重新啓動以控制...]或[這不是[產品名稱]更新文件]。正如你可以想象的,固件更新可能相當大,如果通過3G傳輸需要一段時間。

我想從CSS中獲取產品名稱:在僞類之前允許我在發送之前檢查上傳文件的名稱。我已經實施了這個JS Fiddle來說明這個問題。

我已經嘗試將content屬性直接放在.productname類(作爲副本佔位符)和FF,Opera和Safari將會讀取此內容,但您猜對了它,IE返回undefined。

我知道我可以在JS中使用全局變量,可能必須這樣做,但我寧願將它定義在一個地方以避免潛在的錯誤。

那麼有誰知道如何(或解決方法)讀取僞CSS類的屬性?

在此先感謝。

更新

因爲我不能讓IE8的一個解決方案,我已經改變使用下面的代碼來代替。

window.addEvent("domready", 
function() 
{ 
    window.productName = "My Shiny New Product";  

    var def = '.productname:before { content: "'+window.productName+'"; }'; 

    var style = new Element("style"); 
    style.setAttribute("type", "text/css"); 
    if(style.styleSheet) 
    { 
    style.styleSheet.cssText = def; 
    } 
    else 
    { 
    style.innerHTML = def; 
    } 
    document.getElementsByTagName("head")[0].appendChild(style); 
    document.getElementsByTagName("head")[0].appendChild(style); 
}); 

參照本網站Dynamic SCRIPT and STYLE elements in IE

+0

可能重複http://stackoverflow.com/questions/311052/setting-css-pseudo-class-rules-from-javascript – Manishearth 2012-03-12 11:56:09

+0

你可能想看看http://stackoverflow.com/questions/1543648/how-to-get-a-text-before-given-element-using-jquery – bPratik 2012-03-12 11:56:40

+0

@bPratik - 感謝評論,但用途:在文本不在html文檔之前,我不認爲它可以是以這種方式訪問​​。從Firebug和我的小提琴之前的兄弟姐妹(div)的內容是空的。 – Dampsquid 2012-03-12 12:05:20

回答

2

可以使用window.getComputedStyle。然而,an answer指出,一些瀏覽器可能不支持這一點,所以輕輕一點。 here's a demo

<span class="test" /> 
<span class="test" /> 
<span class="test" /> 

.test:before{ 
    content: "My Shiny New Product"; 
} 

$(function() { 

    //get all element class test 
    var test = $('.test'); 

    //each of them, alert the content 
    test.each(function() { 
     var style = window.getComputedStyle(this, "before"); 
     alert(style.content); 
    }); 
});​ 
+0

謝謝,但測試你的演示它只能在Safari中工作。 FF和Opera警報:無,並且IE失敗且對象不支持該方法。 – Dampsquid 2012-03-12 12:13:18

+1

更改您的代碼以使用getComputedStyle(this,「:before」);使得它可以在除IE之外的所有環境中工作,可悲的是90%以上的客戶將使用IE,而大多數客戶將無法切換到其他瀏覽器。 – Dampsquid 2012-03-12 12:29:03

+0

@Dampsquid我無法測試IE因爲我沒有IE:D。您可以檢查用戶的瀏覽器並使用「之前」或「之前」。 – Joseph 2012-03-12 20:03:02