有人可以向我解释,并帮助我如何使我的cookie按钮只有一次用户接受它。当刷新页面时,我不希望按钮再次出现。我不能做这段代码
HTML代码
<div id="cookieConsent">
<div class="cookieContainer">
<p class="cookieConsent-txt">
This site uses cookies.
</p>
<a class="cookieConsentOK">Accept</a>
</div>
</div>CSS码
#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;
}脚本
$(document).ready(function(){
setTimeout(function () {
$("#cookieConsent").fadeIn(200);
}, 2000);
$("#closeCookieConsent, .cookieConsentOK").click(function() {
$("#cookieConsent").fadeOut(200);
});
}); 发布于 2022-12-02 13:01:48
若要使cookie同意按钮仅在用户接受该按钮之后出现一次,而在刷新页面时不再出现,您可以使用localStorage API存储一个值,指示用户已接受cookie同意。
下面是如何修改代码以实现此目的的示例:
// 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同意按钮。
https://stackoverflow.com/questions/74656110
复制相似问题