2014-11-23 35 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>