如何让我的 cookie 同意横幅为每个用户(ip)弹出一次

Kra*_*ler 4 html javascript css jquery

首先,我知道之前已经回答过类似的问题,但我真的不明白,我现在是 jquery 的一个小人物,我真的不知道如何在我的代码中实现它或了解它是如何工作的。如果有人不仅可以给我解决方案,还可以解释它的作用以及如何做到这一点,那就太棒了。

所以这是我的 HTML

<div id="cookieConsent">
                    This website is using cookies. <a href="#" target="_blank">More info</a>.<a class="cookieConsentOK">That's Fine</a>
</div>
Run Code Online (Sandbox Code Playgroud)

显然,我已经链接了我的脚本文件和 jquery CDN,因此无需显示,现在这是我的 css。

/*Cookie Consent Begin*/
#cookieConsent {
    background-color: rgba(20,20,20,0.8);
    min-height: 26px;
    font-size: 14px;
    color: #ccc;
    line-height: 26px;
    padding: 8px 0 8px 30px;
    font-family: "Trebuchet MS",Helvetica,sans-serif;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: none;
    z-index: 9999;
    text-align: center;
}
#cookieConsent a {
    color: #4B8EE7;
    text-decoration: none;
}
#closeCookieConsent {
    display: inline-block;
    cursor: pointer;
    height: 20px;
    width: 20px;
    margin: -15px 0 0 0;
    font-weight: bold;
}
#closeCookieConsent:hover {
    color: #FFF;
}
#cookieConsent a.cookieConsentOK {
    background-color: #4B8EE7;
    color: white;
    display: inline-block;
    border-radius: 5px;
    padding: 0 20px;
    cursor: pointer;
    margin: 0 60px 0 10px;
    transition: background-color 650ms;
}
#cookieConsent a.cookieConsentOK:hover {
    background-color: #3e75bd;
}
/*Cookie Consent End*/
Run Code Online (Sandbox Code Playgroud)

最后我的工作但烦人的 jquery js 文件

$(document).ready(function(){   
    setTimeout(function () {
        $("#cookieConsent").fadeIn(700);
     }, 1000);
    $(".cookieConsentOK").click(function() {
        $("#cookieConsent").fadeOut(700);
    }); 
}); 
Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助我让每个 IP 或用户会话只显示一次弹出窗口(我的意思是直到他们完全关闭浏览器,也尝试专注于移动设备)并且不仅为我提供解决方案,而且还解释它,我会爱你的!

小智 5

正如评论中所建议的,在对“cookieConsentOk”的响应中,您可以将他们确认 cookie 的信息存储为 cookie 或 localStorage。

使用本地存储:

localStorage.setItem('cookies_enabled', '1'); // Use cookies
Run Code Online (Sandbox Code Playgroud)

或者如果被禁用

localStorage.setItem('cookies_enabled', '0'); // No cookies
Run Code Online (Sandbox Code Playgroud)

您可以通过获取来检查此值

if (localStorage.getItem('cookies_enabled') === '1') {
    // save cookies for session
}
Run Code Online (Sandbox Code Playgroud)

如果出现以下情况,您可以显示横幅:

if (localStorage.getItem('cookies_enabled') === null) {
    // display banner
}
Run Code Online (Sandbox Code Playgroud)