我开发了几个显示在所有网站页面上的警报框。
用户可以单独关闭每个盒子:
$(document).ready(function() {
$("#close-alert-box-news").click(function() {
$("#alert-box-news").hide(800);
});
$("#close-alert-box-maintenance").click(function() {
$("#alert-box-maintenance").hide(800);
});
});
.alert-box {
width: 50vw;
position: relative;
margin: 20px auto;
border: 1px solid black;
}
.alert-box-close {
position: absolute;
top: -12px;
right: -12px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<article class="alert-box" id="alert-box-news">
<h1>News Alerts</h1>
<p>text text text text text text text text text text text text text text</p>
<a class="alert-box-close" id="close-alert-box-news">
<img src="http://i.imgur.com/czf8yas.png" height="25" width="25" alt="">
</a>
</article>
<article class="alert-box" id="alert-box-maintenance">
<h1>Site Maintenance</h1>
<p>text text text text text text text text text text text text text text</p>
<a class="alert-box-close" id="close-alert-box-maintenance">
<img src="http://i.imgur.com/czf8yas.png" height="25" width="25" alt="">
</a>
</article>
jsFiddle
现在我需要确保用户关闭的框(可以是一个,也可以是两个),在他/她浏览网站或重新加载页面时不会重新出现。
我想我可以将 PHP cookie 设置为在 24 小时内过期。但是该站点上的大多数相关帖子都推荐使用 JavaScript cookie。不幸的是,我实现 JavaScript 解决方案的努力没有奏效(这些框在关闭后重新出现)。我尝试了各种方法,如下所述:
- Set cookie to hide div when button is clicked
- Set cookie when my div is hidden
- jQuery Cookie hide/show div
- Hide div 24hr cookie javascript?
在整个站点范围内隐藏每个框 24 小时的简单方法是什么?
我对 jQuery、纯 JavaScript、PHP、cookie、 session 或其他东西持开放态度。
最佳答案
使用 localStorage()
.
本地存储按来源(按域和协议(protocol))
- 点击DIV关闭,可以获得当前时间戳
- 将小时数 (24) 添加到该时间戳
- 将该值存储在
localStorage
中作为localStorage.setItem('desiredTime', time)
- 用存储的时间戳检查当前时间戳
localStorage.getItem('desiredTime')
, 基于show/hide
jQuery
$(document).ready(function(){
//Get current time
var currentTime = new Date().getTime();
//Add hours function
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
//Get time after 24 hours
var after24 = new Date().addHours(10).getTime();
//Hide div click
$('.hide24').click(function(){
//Hide div
$(this).hide();
//Set desired time till you want to hide that div
localStorage.setItem('desiredTime', after24);
});
//If desired time >= currentTime, based on that HIDE / SHOW
if(localStorage.getItem('desiredTime') >= currentTime)
{
$('.hide24').hide();
}
else
{
$('.hide24').show();
}
});
HTML
<div>DIV-1</div>
<div class='hide24'>DIV-2</div>
注意事项
- 您可以使用
$.cookie
同样,但现在这是一种较旧的方法。 -
<div>
与类hide24
只会被隐藏。 - 确保将此代码放在通用 JavaScript 中,它会在您网站的每个 HTTP 请求上加载。
- 对于
localStorage
, 你应该有 HTML5 浏览器。
希望这对您有所帮助。
关于javascript - 隐藏所有站点页面上的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40192296/