首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使我的cookie同意横幅弹出一次给每个用户(Ip)。

如何使我的cookie同意横幅弹出一次给每个用户(Ip)。
EN

Stack Overflow用户
提问于 2022-12-02 12:53:14
回答 1查看 35关注 0票数 1

有人可以向我解释,并帮助我如何使我的cookie按钮只有一次用户接受它。当刷新页面时,我不希望按钮再次出现。我不能做这段代码

HTML代码

代码语言:javascript
复制
<div id="cookieConsent">
        <div class="cookieContainer">
            <p class="cookieConsent-txt">
                This site uses cookies.
            </p>
            <a class="cookieConsentOK">Accept</a>
        </div>      
    </div>

CSS码

代码语言:javascript
复制
#cookieConsent {
    width: 100%;
    background-color: #DAD9DA;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: none;
}

.cookieContainer {
    padding: 20px 15px 20px 15px;
    display: flex;
    align-items: center;
    margin: 0;
}


.cookieConsent-txt {
    text-align: left;
    margin: 0;
}

#cookieConsent a.cookieConsentOK {
    width: 85px;
    height: 56px;
    background: #FFFFFF;
    padding: 4px 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
}

脚本

代码语言:javascript
复制
$(document).ready(function(){   
    setTimeout(function () {
        $("#cookieConsent").fadeIn(200);
        }, 2000); 
    $("#closeCookieConsent, .cookieConsentOK").click(function() {
        $("#cookieConsent").fadeOut(200);
    }); 
}); 
EN

回答 1

Stack Overflow用户

发布于 2022-12-02 13:01:48

若要使cookie同意按钮仅在用户接受该按钮之后出现一次,而在刷新页面时不再出现,您可以使用localStorage API存储一个值,指示用户已接受cookie同意。

下面是如何修改代码以实现此目的的示例:

代码语言:javascript
复制
// First, check if the user has already accepted the cookie consent
// by checking for the presence of the "acceptedCookies" value in localStorage
if (localStorage.getItem("acceptedCookies") === null) {
  // If the user has not accepted the cookie consent, show the cookie consent button
  $(document).ready(function() {   
    setTimeout(function () {
      $("#cookieConsent").fadeIn(200);
    }, 2000); 
    $("#closeCookieConsent, .cookieConsentOK").click(function() {
      // When the user clicks the "Accept" button, hide the cookie consent button
      // and store the "acceptedCookies" value in localStorage
      $("#cookieConsent").fadeOut(200);
      localStorage.setItem("acceptedCookies", "true");
    }); 
  });
}

在本例中,代码首先检查acceptedCookies值是否存在于localStorage中。如果它不存在,则意味着用户尚未接受cookie同意,并显示cookie同意按钮。当用户单击“接受”按钮时,按钮被隐藏,acceptedCookies值存储在localStorage中。即使在刷新页面之后,此值也将持续存在,因此不再显示cookie同意按钮。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74656110

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档