是否可以使用JavaScript设置相同的CSS属性两次?

时间:2018-01-25 15:56:38

标签: javascript css

使用CSS,出于兼容性原因,您可以使用不同的格式两次定义相同的属性。

例如:

body {
    /* Since this is defined first, it will apply for all browsers that don't support the next property. */
    background-color: '#FFF';

    /* Since this is defined last, it will apply for all browsers that support it, and hence will override the previous property. */
    background-color: myFancyColorFunction();
}

有没有什么方法可以通过JavaScript定义两个与inline-CSS相同的属性?

3 个答案:

答案 0 :(得分:0)

我不确定如果我错了,请更正确,但我认为浏览器的工作原理如下:

  1. 找到应该应用于Element
  2. 的类
  3. 尝试将背景颜色设置为'#FFF' - >确定
  4. 尝试将背景颜色设置为myFancyColorFunction() - >例外 3.1捕获异常并继续
  5. ...
  6. 一个Dom元素只能有一种背景颜色,所以技术性更强,这是一种有趣的后备。

    我认为它正在工作(做了一个快速测试):

    
    
    
    

    
    
    document.getElementById("box1").style = 'background: yellow; background: linear-gradient(red, yellow);'
    
    console.log("style", document.getElementById("box1").style.background);
    
    <div id="box1">Test</div>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

我将通过一些假设对此进行扩展,目标是修改实际的样式表值。注意我只在旧计算机上的chrome上测试过它。

这可能是一种可怕的方式。

我的第一个假设是定义的样式表,例如:

&#13;
&#13;
<style id="findme" type="text/css">
  .myfunstuff {
    background-color: darkred;
  }
</style>
<div class="myfunstuff">Howdy fun stuff here</div>
<script type="text/javascript">
  var stylesheet = {};
  // your selector may vary here
  for (var i in document.styleSheets) {
    if (document.styleSheets[i] && document.styleSheets[i].cssRules[0] && document.styleSheets[i].cssRules[0]["selectorText"] && document.styleSheets[i].cssRules[0]["selectorText"] == ".myfunstuff") {
      stylesheet = document.styleSheets[i];
      break;
    }
  }
  stylesheet.cssRules[0].style.backgroundColor = "lightblue";
// now for the "twice" set it to something else
  stylesheet.cssRules[0].style.backgroundColor = "lime";
</script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以根据需要多次调用element.style.x = 'y',并且每次调用它时,都会重置css属性,因为它将内联设置为内联:

<div style="background-color: red"></div>

如果元素(内联)上已存在样式,JavaScript将更新元素上的当前样式,而不是添加为新样式。

这将允许您根据需要多次设置样式,并且在属性x上最后调用的样式将是最终样式。

你可以在这里看到这个例子

&#13;
&#13;
let div = document.querySelector('div')
let colors = ['red', 'yellow', 'green', 'blue']
let i = 0

function setColor() {
  div.style.backgroundColor = colors[i];
  div.textContent = colors[i];
  ++i < colors.length && setTimeout(setColor, 1000)
}

setTimeout(setColor, 1000)
&#13;
body {
  padding: 0;
  margin: 0;
}

div {
  background-color: orange;
  width: 100vw;
  height: 100vh;
  color: white;
  font-size: 3rem;
  text-align: center;
  line-height: 100vh;
}
&#13;
<div>orange - default css</div>
&#13;
&#13;
&#13;