我是这个领域的新手,目前正在建立一个网站。 我用 HTML 和 CSS 创建了一个 cookie 横幅。 我需要知道如何让它对每个用户“例如每 24 小时”只启动一次。
我试着用IP地址来区分不同的用户,但我不知道怎么记住。
为了使您的cookie banner 每24 小时只为每个用户显示一次,您可以使用浏览器cookie 来存储用户的同意信息。以下是您可以如何实施它:
当用户接受 cookie 横幅时,在他们的浏览器中设置一个 cookie,其有效期为从当前时间起 24 小时。
当用户访问你的网站时,检查cookie是否存在,是否还没有过期。如果 cookie 存在且未过期,则不显示 cookie 横幅。否则,显示横幅。
function setCookie(name, value, hours) {
var expires = "";
if (hours) {
var date = new Date();
date.setTime(date.getTime() + hours * 60 * 60 * 1000);
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function showCookieBanner() {
var cookieBanner = document.getElementById("cookie-banner");
if (getCookie("cookieConsent") === null) {
cookieBanner.style.display = "block";
} else {
cookieBanner.style.display = "none";
}
}
function acceptCookies() {
setCookie("cookieConsent", "true", 24);
document.getElementById("cookie-banner").style.display = "none";
}
window.onload = function() {
showCookieBanner();
};