我希望隐藏所有内容,并在特定日期之后在我的网页中显示“测试结束”等文字。我创建了一个函数,但它无法正常工作。请帮我解决这个问题。
<script type="text/javascript">
var myDate=new Date();
myDate.setFullYear(2015,2,14);
var today = new Date();
if (myDate>today)
{
document.body.style.display = "none";
}
</script>
答案 0 :(得分:2)
我能想到的最简单的方法:
var myDate = new Date(),
today = new Date(),
// create an element to contain your content:
note = document.createElement('h1');
// set the content of that created-element:
note.textContent = 'Test Over';
// remember that, in JavaScript, months are zero-indexed,
// 0 = January, 1 = February (you were originally testing
// against a date in March):
myDate.setFullYear(2015, 1, 14);
if (myDate > today) {
// while there's any content in the <body>:
while (document.body.firstChild){
// we remove that content, each time removing the
// firstChild:
document.body.removeChild(document.body.firstChild);
}
// appending the created-element:
document.body.appendChild(note);
}
var myDate = new Date(),
today = new Date(),
note = document.createElement('h1');
note.textContent = 'Test Over';
myDate.setFullYear(2015, 1, 14);
if (myDate > today) {
while (document.body.firstChild){
document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(note);
}
<h1>This text should not be visible</h1>
参考文献:
答案 1 :(得分:0)
如果你想隐藏身体 指定的日期之后,那么你需要检查你的日期是否小于,这意味着它是否通过,而不是其他方式围绕
var myDate = new Date();
myDate.setFullYear(2015, 1, 11);
var today = new Date();
if (myDate < today) {
// this will just replace the body's html with your text
document.body.innerHTML="some text";
}
&#13;
div {
display: inline-block;
width: 200px;
height: 200px;
}
.beforeDate {
background: red;
}
.afterDate {
background: cyan;
}
&#13;
<div class="afterDate">This one will be hidden after the date</div>
&#13;
<强>更新强>
如果你想把你的脚本放在头部,你需要确保它在创建正文中的元素之前没有运行,所以你不会尝试改变那些尚不存在的对象。
你可以通过将一个自定义处理程序附加到文档的加载事件来实现,该加载事件将在加载DOM时触发,并在那里放置脚本:
document.addEventListener("load", function () {
var myDate = new Date();
myDate.setFullYear(2015, 1, 11);
var today = new Date();
if (myDate < today) {
// this will just replace the body's html with your text
document.body.innerHTML = "some text";
}
},true);