将CSS类添加到Javascript代码中

时间:2013-11-24 15:24:34

标签: javascript css

我按照本指南了解如何根据一天中的时间更改背景: https://coderwall.com/p/j3-3ra 同样的指南: http://codepen.io/jamesbarnett/pen/kdDBL

所以我有这些CSS类:

/* backgrounds */
.day { background: url('images/backlarge_snow.png');
fixed top repeat-x;
background-color: #FFFFFF;
}
.sunset { background: url('images/backlarge_afternoon.png');
fixed top repeat-x;
background-color: #FFFFFF;
}
.night { background: url('images/backlarge_night.png');
fixed top repeat-x;
background-color: #bbc1c1;
}

我想让他们进入:

<script type="text/javascript">
$(document).ready(function(){
var d = new Date();
var n = d.getHours();
if (n > 19 || n < 6)
  // If time is after 7PM or before 6AM, apply night theme to ‘body’
  document.body.className = "night";
else if (n > 16 && n < 19)
  // If time is between 4PM – 7PM sunset theme to ‘body’
  document.body.className = "sunset";
else
  // Else use ‘day’ theme
  document.body.className = "day";
});
</script>

如何将CSS文件中的类导入索引中的javascript代码?

2 个答案:

答案 0 :(得分:1)

假设你要做的只是根据n的值对身体应用不同的类。我会使用+ ='someClass',如:

if (n > 19 || n < 6)
  // If time is after 7PM or before 6AM, apply night theme to ‘body’
  document.body.className += " night";
else if (n > 16 && n < 19)
  // If time is between 4PM – 7PM sunset theme to ‘body’
  document.body.className += " sunset";
else
  // Else use ‘day’ theme
  document.body.className += " day";
});

确保你正在添加的课程中有一个空格,这样你就不会搞砸那些已经存在的东西......

答案 1 :(得分:-2)

为什么不在getClass中使用JQuery?

 <script type="text/javascript">
 $(document).ready(function(){
 var d = new Date();
 var n = d.getHours();
 if (n > 19 || n < 6)
 // If time is after 7PM or before 6AM, apply night theme to ‘body’
 $('body').addClass('night');
 else if (n > 16 && n < 19)
 // If time is between 4PM – 7PM sunset theme to ‘body’
 $('body').addClass('sunset');
else
 // Else use ‘day’ theme
 $('body').addClass('day');
 });
 </script>