简体   繁体   中英

Insert css rule with javascript

I would like to change my div background from time of the day with this code,but doesn't working.I want to add it to my embed css(fourth link). It will add to the remaining rule.

var hur = new Date();
    var dyng = hur.getHours()
   if(dyng > 6 && dyng < 18){
     document.styleSheets[3].cssRules[0].style.background="url('/blog/themes/custom/img/sky.jpg')"
   }else{
    document.styleSheets[3].cssRules[0].style.background="url('/blog/themes/custom/img/night.jpg')"
   }

css

#test {
    background-size: cover;
    width: 100%;
    height: 220px;
}

This typically can be achieved in a simple way by using a pair of jQuery methods:

.addClass()
.removeClass()

In a plain Javascript solution the same can be done with a pair of functions:

element.setAttribute ("class", "CSS class name");
element.removeAttribute ("class", "CSS class name");

Using JavaScript to modify CSS is not a good idea.

It's better to have all your styles defined in CSS and have JavaScript select which of those rules gets applying by adding/removing classes.

You can use the .className property for DOM Elements (but I would recommend using a framework).

您也可以使用setAttribute函数。

element.setAttribute('class', 'class name');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM