我是 Javascript 的新手,我想创建以下示例:
基本上,我正在尝试获取可在需要时由用户关闭的自定义内容。我听说这可以使用带有超时期限的 localStorage 来完成。
一旦用户点击关闭按钮,它就会隐藏在 DOM 中,直到计时器到期,比如 2-3 天,然后再次出现在页面中。
我该怎么做?
希望对此有所帮助。
谢谢
最佳答案
您可以为此使用 localStorage。 更简单的方法是使用 cookie,您可以在 cookie 上设置过期时间,它会自动删除。
使用 localStorage 它看起来像这样:
// User has clicked in the past
if (localStorage.userClickExpiration) {
if (Date.now() > parseInt(localStorage.userClickExpiration)) {
// Time expired, reset the localStorage and show the element
localStorage.removeItem('userClickExpiration');
$('.element').show();
} else {
$('.element').hide();
}
}
// User click handler
function handleClick() {
// Store the time when the auto hide will be expired, now + 2 days in milliseconds
localStorage.userClickExpiration = Date.now() + (2 * 24 * 60 * 60 * 1000);
// Hide the element using jQuery
$('.element').hide();
}
关于javascript - 如何使用带超时的 localStorage 创建元素显示和隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37906737/