How do I add a class without having it get rid of

2019-04-16 00:36发布

I have the following code set up in my footer which adds a class of 'day' during the time specified.

function setTimeStyles() {
    var currentTime = new Date().getHours();
    if(currentTime > 5 && currentTime < 17) {
    document.body.className = 'day';
    }
}

$(document).ready(function() {
    setTimeStyles();
});

The problem is when the class gets added, it gets rid of the other classes already in place. For example, without the 'day' class added, my body tag would be:

<body class="home">

But when the 'day' class is added, my body tag turns into:

<body class="day">

I'd like it so that the 'day' class gets added to what's already there like this:

<body class="home day">

How can I go about doing this?

3条回答
爷的心禁止访问
2楼-- · 2019-04-16 01:11

In jQuery you can do

$("body").addClass("day");
查看更多
叛逆
3楼-- · 2019-04-16 01:14

Have you tried replacing

document.body.className = 'day'; 

with

document.body.className = document.body.className + ' day';
查看更多
贼婆χ
4楼-- · 2019-04-16 01:16

I don't know how jquery adds a class, but you may want to be sure it is added (or moved) to the end of any existing list, giving it precedence in any collisions.

function addClass(node, cname){
 var C= node.className.split(/\s+/), L= C.length;
 while(L){
  if(C[--L]=== cname) delete C[L];
 }
 C.push(cname);
 node.className= C.join(' ').replace(/ {2,}/g,' ');
}
查看更多
登录 后发表回答