2015-09-29 32 views
1
.a:before { 
    content: 'b'; 
    display: table; 
     } 

如何獲得類'a'的內容值?我嘗試:獲取僞類的價值

`var b = window.getComputedStyle(document.querySelector('a'), ':before').getPropertyValue('content');` 

這回我一個錯誤:

Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'. 
+1

認爲你錯過了點... querySelector('。a') – Chris

+0

或在他的CSS一個額外的'。 – lshettyl

回答

1

像其他人指出的那樣,你在你的選擇a之前缺少點。正確的代碼應該是這樣的:

var text = getComputedStyle(document.querySelector('.a'), ':before').getPropertyValue('content'); 
 
alert(text);
.a:before { 
 
    content: 'b'; 
 
    display: table; 
 
}
<div class="a"></div>

作爲一般的調試策略,這是分裂較小的部分不再陳述,以確定什麼是錯在你的代碼是一個好主意。 例如,在這裏你可以重寫你的JavaScript爲:

var a = document.querySelector('a'); 
var computedStyle = window.getComputedStyle(a, ':before'); 
var content = computedStyle.getPropertyValue('content'); 

這樣,我們立即看到a,在第一條語句指定的值,實際上是null,並解釋在第二條語句的類型錯誤。 這可以減少document.querySelector('a')?中出現問題的問題,這相當容易處理。

1

要訪問一個CSS僞類的內容屬性是這樣的:

.a::before { 
    content: 'b'; 
    display: table; 
} 

您可以使用此javascript:

window.getComputedStyle(document.querySelector('.a'),':before').getPropertyValue('content'); 

確保CSS在CSS僞類有::和querySelector使用了一個點('.a')

這裏是一個工作FIDDLE

+0

謝謝你的回答。 :) –