2009-07-23 67 views
7

在我的页面上,我通过JavaScript更改了一些CSS样式。当我尝试并拉取一个已被继承的值时,它会变成空白。考虑以下几点:通过Javascript继承CSS值

.Sliding 
    { 
     display: none; 
     overflow: hidden; 
    } 

    .Sliding #FilterBox 
    { 
     height: 185px; 
     background-color: Fuchsia; 
    } 

和HTML:

<div class="Sliding" id="FilterBox"> 
     <h3>Test Form</h3> 
     This is a test/<br /> 
     12345 
</div> 

如果我看元素 '的document.getElementById(objname表).style.display' 的空白?如何通过javascript读取显示值?

+0

谢谢大家。使用getComputedStyle帮助解决了我的问题。我将它作为getElementById()。style仅用于各个样式设置 - 不是由类或ID设置的样式。 – cschear 2009-07-24 07:14:18

回答

8

您需要使用getComputedStyle

.style属性是一种访问和设置内联样式(即样式属性)的方法。

但是请注意,您的示例与继承无关。只是直接适用于您感兴趣的元素的规则集。继承是指元素通过inherit关键字采用与其父元素相同的样式。

span { 
    color: inherit; 
} 

getComputedStyle会给出最终的计算值,所以它也会选择继承的值。

+2

getComputedStyle()在所有流行的浏览器中都不起作用(没有命名) – 2009-07-23 06:43:16

+2

您现在可以安全地使用'getComputedStyle' http://caniuse.com/#feat=getcomputedstyle – Ivan 2015-04-07 17:41:22

1

你需要看一下计算样式,see here

2

你的第二个CSS规则:

.Sliding #FilterBox 
{ 
    height: 185px; 
    background-color: Fuchsia; 
} 

将匹配ID为“FilterBox”,即与一类“滑动体”的任何后代什么,所以这条规则并不适用于您的股利。

而得到计算样式,你可以参考法比安斯基的答案,或者考虑使用jQuery,这使得这个东西容易得多:使用jQuery,$(“#FilterBox”)

CSS(”显示“)将返回”显示“的当前值。

+0

-1公平的评论 - 但这不是回答。 – Quentin 2009-07-23 06:37:28

+0

当然,但你可以指向他计算风格一百万次,但如果CSS不正确,这是浪费时间 – 2009-07-23 06:39:15

+0

由于第二条规则不触及显示属性,所以它不会有任何影响,如果它是写成适用于该元素。 – Quentin 2009-07-23 06:44:18

0
if (!window.getComputedStyle) 
{ 
    window.getComputedStyle = function(el, pseudo) 
    { 
     this.el = el; 
     this.getPropertyValue = function(prop) { 

     var re = /(\-([a-z]){1})/g; 
     if (prop == 'float') 
      prop = 'styleFloat'; 
     if (re.test(prop)) 
     { 
      prop = prop.replace(re, function() { 

      return arguments[2].toUpperCase(); 
      }); 
     } 

     return el.currentStyle[prop] ? el.currentStyle[prop] : null; 
     } 

     return this; 
    } 
} 

function GetCompStyle() 
{ 
    var compStyle = window.getComputedStyle(document.getElementById('FilterBox'), ""); 
    alert(compStyle.getPropertyValue("display")); 
}