我目前使用以下代码在 5 秒后隐藏页面上的特定元素。但是当刷新页面时,元素再次弹出。
我如何扩展我的代码,以便它在整个生命周期内(或当浏览器缓存被清除时)隐藏
代码:
<script type="text/javascript">
setTimeout(function() {
$('#data-popup-box-container').fadeOut('fast');
}, 5000);
</script>
最佳答案
可以使用以下方法实现在生命周期内隐藏元素
- 隐藏弹出窗口时,设置 Localstorage 键
- 在文档就绪时检查 Localstorage 键是否存在,直接删除元素
示例代码:
<script type="text/javascript">
/* Your existing code + store entry in LocalStorage */
setTimeout(function() {
$('#data-popup-box-container').fadeOut('fast');
// Add entry in localstorage that Popup displayed once :)
localStorage.setItem("popupDisplayed", "yes");
}, 5000);
/* On reload check if localstorage value is yes :) */
$( document ).ready(function() {
var popupDisplayed = localStorage.getItem("popupDisplayed");
/* If local storage value is yes - remove element directly from dom */
if(popupDisplayed && popupDisplayed == 'yes') {
$('#data-popup-box-container').remove();
}
});
</script>
更新::
正如@inetphantom 在他的评论中所建议的那样,如果连接缓慢,则永远不会显示弹出窗口。因此,您隐藏弹出窗口的代码应该是
/* Check if all resource are loaded */
$(window).load(function() {
setTimeout(function() {
$('#data-popup-box-container').fadeOut('fast');
// Add entry in localstorage that Popup displayed once :)
localStorage.setItem("popupDisplayed", "yes");
}, 5000);
});
阅读有关窗口加载的更多信息 here
关于javascript - jQuery 隐藏生命周期浏览器 cookie 的 div 弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56754900/