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

微笑、不失礼 提交于 2019-12-21 23:06:54

问题


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?


回答1:


In jQuery you can do

$("body").addClass("day");



回答2:


Have you tried replacing

document.body.className = 'day'; 

with

document.body.className = document.body.className + ' day';



回答3:


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,' ');
}


来源:https://stackoverflow.com/questions/4660590/how-do-i-add-a-class-without-having-it-get-rid-of-the-others

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!