JavaScript根据星期几更改div的CSS属性

时间:2017-07-27 15:24:12

标签: javascript jquery html css

我正在创建一个网站。我显示营业时间。并且客户要求突出显示当周的当天.E.G。每天都会显示在黑色框中,但今天的日期显示在红色框中。

var d = new Date();
var weekday = new Array(7);
weekday[0] =  "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()];

if (n = 'Thursday') {
    $('coloured-box').css({"color":"green"});
}

以上是我不知道它是对还是差不多。

2 个答案:

答案 0 :(得分:9)

最简单的方法是获取当前日期,然后通过其容器中的索引在给定元素上设置类,如下所示:

$('.coloured-box span').eq(new Date().getDay()).addClass('today');
.coloured-box span.today { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="coloured-box">
  <span>Sunday</span>
  <span>Monday</span>
  <span>Tuesday</span>
  <span>Wednesday</span>
  <span>Thursday</span>
  <span>Friday</span>
  <span>Saturday</span>
</div>

答案 1 :(得分:0)

我认为你可能有一个逻辑错误。

if (n = 'Thursday') {
    $('coloured-box').css({"color":"green"});
}

您需要使用==

进行比较
if (n == 'Thursday') {
    $('coloured-box').css({"color":"green"});
}