jQuery 隐藏 div 弹出窗口以获得终身浏览器 cookie

Hen*_*k Z 1 javascript jquery local-storage

我目前使用以下代码在 5 秒后隐藏页面上的特定元素。但是当刷新页面时,元素再次弹出。

如何扩展我的代码,使其终生隐藏(或清除浏览器缓存时)

代码:

<script type="text/javascript">
    setTimeout(function() {
  $('#data-popup-box-container').fadeOut('fast');
}, 5000);   
</script>
Run Code Online (Sandbox Code Playgroud)

Kru*_*hal 5

可以使用以下方法来实现终身隐藏元素

  1. 当您隐藏弹出窗口时,设置一个 Localstorage 键
  2. 在文档就绪时检查 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>
Run Code Online (Sandbox Code Playgroud)

更新::

根据@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);
    });
Run Code Online (Sandbox Code Playgroud)

此处阅读有关窗口加载的更多信息