开发者

Add different classes to divs with jQuery depending on the time in the div and current time?

I am creating a little TV guide for myself and I have a list of programs from a TV channel that runs today. What I now try to do is to add three different CSS classes, one for the program that is currently o开发者_StackOverflow中文版n air (.present), one for shows before the current one (.past) and one for the shows after the current one (.future).

I get the current time with

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
for (var i = 2; i--; )
    curr_min[i] = ("0" + curr_min[i]).slice(-2);
var curr_time = curr_hour + ":" + curr_min;

The HTML looks something like:

<div class="title">15:00 - Show 1</div>
<div style="display: none;" class="description">Information about show 1.</div>
<div class="title">15:30 - Show 2</div>
<div style="display: none;" class="description">Information about show 2.</div>
<div class="title">16:00 - Show 3</div>
<div style="display: none;" class="description">Information about show 3</div>

So if curr_time is 15:45 I want the div with Show 2 to have an extra class .present, the div with show 1 the extra class .past and the div with Show 3 the extra class .future. So, something like:

<div class="title past">15:00 - Show 1</div>
<div style="display: none;" class="description">Information about show 1.</div>
<div class="title present">15:30 - Show 2</div>
<div style="display: none;" class="description">Information about show 2.</div>
<div class="title future">16:00 - Show 3</div>
<div style="display: none;" class="description">Information about show 3</div>

How can I achieve this with jQuery?


Loop through the elements, get the time and add a class based on that:

var before = 'present';
$($('.title').get().reverse()).each(function(){
  var time = $(this).html();
  time = time.substr(0, time.indexOf(' '));
  if (time <= curr_time) {
    $(this).addClass(before);
    before = 'past';
  } else {
    $(this).addClass('future');
  }
});

Edit:

Changed the code to loop in reverse, to get the present class in the right place.


You cycle through the titles, get the text of the title with .text(), use a regexp to extract the time (something like /^(\d+):(\d+).*$/) and set it to past if the time is smaller or equal than the current time, and future if it is greater. Then you change the last past element to present.

var curr_time = curr_hour * 60 + curr_min;
$('.title').each(function() {
    var m = $(this).text().match(/^(\d+):(\d+).*$/);
    if (!m) { // malformed time?
        return;
    }
    var time = m[1] * 60 + m[2];
    $(this).addClass(time <= curr_time ? 'past' : 'future');
});
$('.past:last').removeClass('past').addClass('present');

Might need some adjustment for programs after midnight.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜