1. 首先,在 HTML 中添加弹窗的代码,并设置一个 id,方便通过 JavaScript 操作:
<div id='cookie-popup'>
  <p>我们使用 cookie 来提供更好的用户体验和服务。点击'同意'继续使用。</p>
  <button id='cookie-agree'>同意</button>
</div>
  1. 接下来,在 CSS 中设置弹窗的样式,可以根据自己的需求进行调整:
#cookie-popup {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #f5f5f5;
  padding: 20px;
  text-align: center;
  font-size: 16px;
  z-index: 9999;
}
#cookie-agree {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}
  1. 最后,在 JavaScript 中实现点击关闭后一天弹一次的功能:
// 获取弹窗元素和同意按钮元素
var cookiePopup = document.getElementById('cookie-popup');
var cookieAgree = document.getElementById('cookie-agree');

// 判断是否已经同意过,如果没有同意过,则显示弹窗
if (getCookie('cookieAgree') == null) {
  cookiePopup.style.display = 'block';
}

// 点击同意按钮,设置 cookie 并关闭弹窗
cookieAgree.onclick = function() {
  setCookie('cookieAgree', 'true', 1);
  cookiePopup.style.display = 'none';
}

// 获取 cookie 的函数
function getCookie(name) {
  var arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
  if (arr = document.cookie.match(reg)) {
    return unescape(arr[2]);
  } else {
    return null;
  }
}

// 设置 cookie 的函数
function setCookie(name, value, days) {
  var exp = new Date();
  exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
  document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString();
}

以上代码中,我们通过 getCookie 函数判断是否已经同意过,如果没有同意过,则显示弹窗。当用户点击同意按钮后,我们通过 setCookie 函数设置 cookie,并关闭弹窗。通过设置 cookie 的过期时间为一天,可以实现点击关闭后一天弹一次的功能。

使用 HTML、CSS 和 JavaScript 实现 Cookie 弹窗,点击关闭后一天弹一次

原文地址: https://www.cveoy.top/t/topic/mMUQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录