javascript Java脚本在两小时和两分钟之间的div上添加类

bt1cpqcv  于 2023-02-21  发布在  Java
关注(0)|答案(3)|浏览(91)

如何添加类与js之间,如14.15和16.15?我有这样的东西:

var currentTime = new Date().getHours();
if (document.body) {
  if (14 <= currentTime && currentTime < 16) {
    var d = document.getElementById("div1");
    d.className += "active";
  } else {

  }
}
<div id="div1">

</div>

如何添加分钟?

nimxete2

nimxete21#

你说加课是什么意思?
也许这就是你正在寻找的:

document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyClass');
ogsagwnx

ogsagwnx2#

你可以这样做:

var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();

if (
  currentHour >= 14 && currentHour <= 16 &&
  (
    (currentHour == 14 && currentMinute >= 15) ||
    (currentHour == 16 && currentMinute <= 15)
  )
) {
  // it is between 14:15 and 16:15
  var d = document.getElementById("div1");
  d.className += "active";
}
ttcibm8c

ttcibm8c3#

我认为您应该使用js Date对象。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
您应该使用元素的classList属性来管理类。https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
我们可以使用3个日期对象(我确信可以使用快捷方式来使用更少的对象)。我们将使用一个作为“现在”,一个作为“今天14:15:00”,一个作为“今天16:15:00”。我们可以很容易地测试“现在”对象是否在开始和结束时间对象的范围内:

const dateNow = new Date();
const windowStart = new Date();
const windowEnd = new Date();
// this is offset in the sandbox
windowStart.setHours(14, 15, 0);
windowEnd.setHours(16, 15, 0);

// force for debug: un comment to verify the check below
//dateNow.setHours(15,00,00);

//debugging only
console.log(`Start of window is: ${windowStart}`);
console.log(`Now time is: ${dateNow}`);
console.log(`End of window is: ${windowEnd}`);

//check to see if we are within the window of time
if (windowStart <= dateNow && dateNow <= windowEnd) {
  console.log(`we are inside the window`);
  var d = document.getElementById("div1");
  d.classList.add("active");
} else {
  console.log(`we are outside the window`);
}

相关问题