2014-11-23 36 views
0

可以說我有一個div風格的外部這樣如何獲得外部風格的元素與JavaScript中的CSS屬性

.box{ 
    background: red; 
} 

那麼也許在javascript我想切換背景顏色,所以我要檢查第一,如果有應用

var box = document.querySelector('.box'); 

if(box.style.background=='red'){ 

box.style.background='pink'; 
}else{ 
box.style.background='red'; 

} 

注意前partcular背景色:我不使用這個發展只是一個js學生

要添加一個很小的問題,如果我想AP多層css過渡到背景變化將如何應用。

下面的代碼工作,雖然,但我覺得有一個更清潔的方式

if(!box.style.background){ //this is because background property is null when reading from external css 

    box.style.background='pink'; 

}else{ 

    box.style.background=""; 
} 

,但過渡,我試圖將過渡

box.style.WebkitTransition='background 0.5s easeout'; 

但沒有轉變

+1

向** **一個每個問題的問題。 – 2014-11-23 09:22:50

+0

@ T.J.Crowder好的,我現在就做到這一點 – user2666633 2014-11-23 09:23:57

+0

您可以使用「編輯」鏈接來修復它。 – 2014-11-23 09:35:22

回答

0

要獲得計算元素的樣式(例如,應用樣式表),您使用getComputedStyle

var box = /*...get a specific element...*/; 
var style = getComputedStyle(box); 
// Use the properties on `style`, which are like the ones on `element.style` 

在較舊的IE上,您改用元素的currentStyle屬性。您可以部分地填充工具getComputedStyle這樣的:

if (!window.getComputedStyle) { 
    window.getComputedStyle = function(element, pseudoElement) { 
     if (pseudoElement) { 
      throw "The second argument for getComputedStyle cannot be polyfilled"; 
     } 
     return element.currentStyle; 
    }; 
} 

例子:

if (!window.getComputedStyle) { 
 
    window.getComputedStyle = function(element, pseudoElement) { 
 
    if (pseudoElement) { 
 
     throw "The second argument for getComputedStyle cannot be polyfilled"; 
 
    } 
 
    return element.currentStyle; 
 
    }; 
 
} 
 

 

 
var foo = document.getElementById("foo"); 
 
var style = getComputedStyle(foo); 
 
if (style) { 
 
    snippet.log("Current color of #foo is: " + style.color); 
 
}
.box { 
 
    color: green; 
 
}
<div id="foo" class="box">This is a box</div> 
 
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

相關問題