JS使用cookie实现DIV提示框只显示一次的方法可以分为以下几个步骤:
JS使用cookie实现DIV提示框只显示一次的方法可以分为以下几个步骤:
- 判断cookie是否存在
- 如果cookie不存在,则显示DIV提示框,并设置cookie
- 如果cookie存在,则不显示DIV提示框
具体步骤如下:
- 判断cookie是否存在:
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) {
return unescape(arr[2]);
}
return null;
}
var isShow = getCookie("isShow");
if (isShow != null && isShow == "false") {
// do not show div
} else {
// show div
}
- 如果cookie不存在,则显示DIV提示框,并设置cookie:
function setCookie(name, value, day) {
var expires = "";
if (day) {
var date = new Date();
date.setTime(date.getTime() + day * 24 * 60 * 60 * 1000);
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + escape(value) + expires + "; path=/";
}
var isShow = getCookie("isShow");
if (isShow == null) {
// show div
setCookie("isShow", "false", 30); // 30 days
}
- 如果cookie存在,则不显示DIV提示框:
var isShow = getCookie("isShow");
if (isShow != null && isShow == "false") {
// do not show div
} else {
// show div
}
以下是两个示例:
- 示例一:
<div id="tip" style="display:none;">This is a div tip.</div>
<script>
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) {
return unescape(arr[2]);
}
return null;
}
function setCookie(name, value, day) {
var expires = "";
if (day) {
var date = new Date();
date.setTime(date.getTime() + day * 24 * 60 * 60 * 1000);
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + escape(value) + expires + "; path=/";
}
var isShow = getCookie("isShow");
if (isShow == null) {
// show div
setCookie("isShow", "false", 30); // 30 days
document.getElementById("tip").style.display = "block";
}
</script>
- 示例二:
<div id="tip" style="display:none;">This is a div tip.</div>
<script>
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) {
return unescape(arr[2]);
}
return null;
}
var isShow = getCookie("isShow");
if (isShow != null && isShow == "false") {
// do not show div
} else {
// show div
document.getElementById("tip").style.display = "block";
}
document.getElementById("close-btn").onclick = function() {
document.getElementById("tip").style.display = "none";
setCookie("isShow", "false", 30); // 30 days
};
</script>
在示例二中,还增加了一个点击关闭按钮后设置cookie的功能,确保用户可以关闭DIV提示框之后不再显示。
织梦狗教程
本文标题为:JS使用cookie实现DIV提示框只显示一次的方法


基础教程推荐
猜你喜欢
- layui数据表格-通过点击按钮使数据表格中的字段值增加 2022-12-16
- js脚本获取webform服务器控件的方法 2023-12-01
- ajax跨域访问报错501的解决方法 2023-01-26
- Vue项目问题——vue-router重写push方法,解决相同路径跳转报错 2023-10-08
- window.location.hash 属性使用说明 2024-01-08
- 用js小类库获取浏览器的高度和宽度信息 2023-12-19
- ajax上传多图到php服务器的方法 2023-02-14
- Nuxt.js中让vuex数据持久化,实测管用 2023-10-08
- CSS清除浮动的常用方法优缺点分析 2024-01-25
- JavaScript实现读取上传视频文件的时长和第一帧画面过程讲解 2023-07-09