使用javascript

时间:2018-11-16 21:24:10

标签: javascript calendar

我目前正在我的学校项目(交互式日历)上工作,但遇到了问题。我需要根据当前日期使日历突出显示表格中的单元格。例如:明天是17日,所以我希望第17个单元格以任何颜色突出显示。我只需要使用javascript和html即可。我有31个用HTML编写的td选择器的表。 我想知道这样的事情: document.getElementsByTagName(“ td”)[Current_Day] .setAttribute(“ background-color”,“ red”);

1 个答案:

答案 0 :(得分:0)

巧合的是,几年前我做了这样的事情:

https://github.com/Subterrane/calendar

此示例代码不是最漂亮的(从Typescript编译而来),但从本质上讲,您是正确的。找到一天,设置颜色。

"use strict";
document.addEventListener("DOMContentLoaded", function(event) {
  var calendars = document.getElementsByTagName('calendar');
  for (var ix = 0; ix < calendars.length; ix++) {
    var calendarEl = calendars[ix];
    var now = new Date();
    var y = parseInt(calendarEl.getAttribute('year')) || now.getFullYear();
    var m = parseInt(calendarEl.getAttribute('month')) || now.getMonth() + 1;
    var d = parseInt(calendarEl.getAttribute('day')) || now.getDate();
    var time = new Date(y, m - 1, d);
    var month = time.getMonth();
    var week = 1;
    var day = 1;
    var html = "<year number=\"" + y + "\"><month number=\"" + m + "\"><week number=\"" + week + "\">";
    time.setDate(day);
    do {
      if (time.getDay() % 7 === 0)
        html += "</week><week number=\"" + ++week + "\">";
      html += "<day number=\"" + day + "\"></day>";
      time.setDate(++day);
    } while (month === time.getMonth());
    html += '</week></month>';
    calendarEl.innerHTML = html;
    calendarEl.querySelector('day[number="' + d + '"]').classList.add('today');
  }
  var days = document.querySelectorAll('day');
  for (var ix = 0; ix < days.length; ix++) {
    days[ix].addEventListener('click', dayClicked);
  }
});

function dayClicked() {
  var el = this;
  var data = {
    year: el.parentElement.parentElement.parentElement.getAttribute('number'),
    month: el.parentElement.parentElement.getAttribute('number'),
    week: el.parentElement.getAttribute('number'),
    day: el.getAttribute('number')
  };
  var event = new CustomEvent('calendarClicked', {
    'detail': data
  });
  document.dispatchEvent(event);
}
calendar {
  display: block;
  margin-top: 20px;
  max-width: 600px;
  font-family: sans-serif;
}

week {
  display: flex;
}

week:first-child {
  justify-content: flex-end;
}

day {
  flex-basis: 14.3%;
  box-sizing: border-box;
  background-color: gainsboro;
  border: 1px solid white;
  padding: 2%;
  color: white;
  cursor: pointer;
  font-size: 4vw;
}

day::after {
  content: attr(number);
}

.today {
  background-color: gold;
}
<div class="container">
  <calendar></calendar>
</div>