如上所述,默认情况下使用CSS隐藏div。到目前为止我有这个脚本:
<script type="text/javascript">
function makeDate(){ // makes the date and defines "today" variable for data-display-before" and "data-display-after" to work. also logs todays date to console for troubleshooting
var now = new Date();
var day = now.getDate();
var month = now.getMonth()+1;
today = month+"-"+day;
var x = document.querySelectorAll(".date-display-after").getAttribute();
var y = document.querySelectorAll(".date-display-before").getAttribute();
console.log("the date today in MM/DD format is "+today); //for troubleshooting
if (today >= x && today <= y){ //the juicy bit
document.getElementById(".hidden").style.display = 'block';
}
}
//setInterval("makeDate()", 3000);
</script>
我怀疑这不起作用,因为我无法将整数与字符串进行比较?无论是那个问题还是问题都是语法问题。我试图按照我在相关帖子上的回答来阅读&#34;在有问题的div中添加两个属性,例如data-display-after和data-display-before,例如:
<div id="valentines"
data-display-after="2016-02-14 00:00:00"
data-display-before="2016-02-15 00:00:00">...Hide these divs initially (with CSS).
在页面加载时,将当前日期(新日期)转换为上述格式。
对于文档中具有data-display-before属性的每个元素(您需要querySelectorAll),比较属性值(getAttribute)和
if currentDate >= data-display-after && currentDate <= data-display-after,
then show the element."
我很欣赏一些关于如何最好地处理变量的建议。下面是HTML的样子:
<body onload="makeDate()">
<div class="occasion" id="hidden" date-display-after="02-01" date-display-before="02-15">
<div class="textbox"><h5>Valentines day</h5><p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime nobis non veritatis quaerat eveniet, necessitatibus, assumenda alias in voluptatum eius voluptate beatae doloribus sed rem officiis ullam perspiciatis earum, aliquam.</span>
<span>Incidunt officiis eligendi quisquam debitis! Vitae voluptates cum architecto culpa voluptatum nam excepturi laborum. Omnis quasi aut ea explicabo, porro quisquam reiciendis animi, mollitia, et error earum tempora, ad asperiores.</span>
<span>Commodi necessitatibus et atque odio eos, itaque quaerat, unde animi, provident deserunt quisquam fugit porro fugiat blanditiis quibusdam culpa quo deleniti molestiae numquam dignissimos alias! Inventore libero incidunt, alias possimus!</span></p></div>
<div class="picture"></div>
div应该在今天可见,因为控制台输出:
the date today in MM/DD format is 2-5
答案 0 :(得分:1)
如果我理解正确,用户看不到时间计算,那么为什么需要将所有内容转换为MM / DD格式?将开始日期和结束日期转换为时间并将它们与现在进行比较会更容易
//Get current time
var d = new Date();
//get year
var y = d.getFullYear();
//Convert to milliseconds
var n = d.getTime();
//Convert dates to date objects
var x = y + '-01-14T00:00:00';
var s = new Date(x);
var y = y + '-02-15T00:00:00';
var e = new Date(y);
//Convert to milliseconds
var start = s.getTime();
var end = e.getTime();
//compare
if (n >= start && n <= end) {
console.log('show hidden div');
}