【问题标题】:How to get a css property of an externally styled element with javascript如何使用 javascript 获取外部样式元素的 css 属性
【发布时间】:2014-11-23 09:21:05
【问题描述】:

假设我有一个像这样的外部 div 样式

 .box{
  background: red;
 }

然后也许在javascript中我想切换背景颜色,所以我必须先检查它是否有特定的背景颜色,然后再应用

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

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

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

}

注意:我不是用这个来开发的,只是一个 js 学生

添加一个小问题,如果我想将 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';

但没有过境

【问题讨论】:

  • 每个问题问 一个 问题。
  • @T.J.Crowder 好的,我现在就这样做
  • 您可以使用“编辑”链接来修复它。

标签: javascript html css


【解决方案1】:

要获得元素的 computed 样式(例如,应用样式表),您可以使用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>

【讨论】:

    猜你喜欢
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多