您好SO社区,
我认为这可能是一个业余类型的问题,但我无法在任何地方找到合适的解决方案:
我试图通过JavaScript在圣诞节时间显示特定的DIV。到目前为止,这里是我的代码:
function WinterTime() {
var WinterStart = new Date(2017, 12, 21);
var WinterEnd = new Date(2017, 12, 27);
if
(WinterStart <= CurrentDate && CurrentDate <= WinterEnd) {
song2.style.display = "block";
}
else {
song2.style.display = "none";
}
}
我定义了变量&#34; song2&#34;如果你想知道,那就更早。
我认为这可能是完整的垃圾代码,但请表示怜悯,因为我是一个完全的菜鸟,只是试图从各种其他威胁中学习。 我很感谢您的反馈。 :)
此致
Jonas
答案 0 :(得分:0)
你有什么应该工作,但我已经清理了一下。我使用控制台日志记录来显示评估的工作方式,您可以根据需要调整以使用HTML。
function winterTime(currentDate) {
var winterStart = new Date(2017, 12, 21);
var winterEnd = new Date(2017, 12, 27);
if(winterStart <= currentDate && currentDate <= winterEnd) {
// current date is within range
console.log('true')
} else {
// current date is out of range
console.log('false')
}
}
winterTime(new Date()); // now
winterTime(new Date(2017, 12, 25)); // within range
答案 1 :(得分:0)
你的逻辑很好,但实现有点偏。 ; - )
// Function names starting with a capital letter are,
// by convention, reserved for constructors.
// The function should accept a date or default to the current date
function winterTime(currentDate) {
currentDate = currentDate || new Date();
// Months are zero indexed, so for 21 December:
var winterStart = new Date(2017, 11, 21);
var winterEnd = new Date(2017, 11, 27);
// Get a reference to the element
var song2 = document.getElementById('song2');
if (winterStart <= currentDate && currentDate <= winterEnd) {
// Set display to '' (empty string) so the element adopts its default or inherited value
song2.style.display = "";
console.log('Winter');
} else {
song2.style.display = "none";
console.log('Not winter');
}
}
// Call function when page loaded
window.onload = winterTime;
&#13;
<div id="song1">Song 1</div>
<div id="song2">Song 2</div>
&#13;
如果您使用最近添加的一些功能,则可以非常简单地使用CSS来应用该样式:
function winterTime(currentDate = new Date()) {
var winterStart = new Date(2017, 11, 21);
var winterEnd = new Date(2017, 11, 27);
var isWinter = winterStart <= currentDate && currentDate <= winterEnd;
var song2 = document.getElementById('song2');
song2.classList[isWinter? 'remove' : 'add']('hidden');
// Just for testing
console.log(isWinter? 'Winter' : 'Not winter');
}
// Call function when page loaded
window.onload = function() {
winterTime(new Date(2017, 11, 25)); // Christmas day
};
&#13;
.hidden {
display: none;
}
&#13;
<div id="song1">Song 1</div>
<div id="song2">Song 2</div>
&#13;