如何在网页上隐藏按钮12个小时?这是我到目前为止的内容:
var now = new Date();
var millisTill20 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 20, 0, 0, 0) - now;
if (millisTill20 < 0) {
millisTill20 += 86400000;
}
console.log('millisTill20 ' + millisTill20);
setTimeout(function() {
$("#button_online").hide();
}, millisTill20);
在20:00脚本运行时,它确实隐藏了元素,但是当我刷新页面时,按钮又回来了。
我遇到了另一个问题,如果某个用户在20:01进入我的网站,他可以看到该按钮,该如何解决?
我了解这是因为我使用的是客户端脚本,但是由于使用的是Salesforce,所以无法使用服务器端。
最佳答案
下面的代码将完成此工作,而无需使用setTimeout()。
var currentDate = new Date();
var currentHour = currentDate.getHours();
if(currentHour>19 || currentHour<9) {
$("#button_online").remove(); // it is better to remove than hide, beacuse someone on client side can still use the button if it is there.
}
W3上的getHours()函数:http://www.w3schools.com/jsref/jsref_gethours.asp
上面的代码将删除页面加载上的按钮。
但是可能会有这样的情况:
现在是19:59,客户端加载了该页面,该按钮未删除。然后是20:00,但按钮仍然存在,因为页面在19:59加载。
如果您也想检查这种情况,可以将上面的代码包装在一个函数中并定期重复执行:
$(document).ready(function() {
checkTheTime();
})
function checkTheTime() {
var currentDate = new Date();
var currentHour = currentDate.getHours();
if(currentHour>19 || currentHour<9) {
$("#button_online").remove(); // it is better to remove than hide, beacuse someone on client side can still use the button if it is there.
}
setTimeout(checkTheTime, 1000);// period=1 second;
}