javascript中Cookie、BOM、DOM的使用
Cookie
在客户端存储小型文本数据(通常 ≤ 4KB),常用于会话管理、个性化设置等场景。
名称 | 描述 | 作用 | 生命周期 | 存储位置 | 安全性 |
---|---|---|---|---|---|
会话 Cookie | 临时存储,浏览器关闭后自动删除 | 会话管理、个性化设置 | 浏览器关闭 | 内存 | 高 |
持久 Cookie | 设置过期时间,长期保存在硬盘 | 免登录、用户偏好设置 | 过期时间 | 硬盘 | 中 |
第三方 Cookie | 由非当前访问网站设置 | 跨站行为追踪 | 浏览器关闭 | 硬盘 | 低 |
- 默认情况下的cookie是内存cookie,也称之为会话cookie,也就是在浏览器关闭时会自动被删除
- 如果想要设置持久cookie,需要设置过期时间,或者设置为永久cookie,也就是在浏览器关闭时不会自动被删除
- 我们可以通过设置expires或者max-age来设置过期的时间,单位为秒,例如expires=Thu, 01 Jan 1970 00:00:00 GMT,或者max-age=0,这样就会设置为永久cookie
- expires:设置的是Date.toUTCString(),设置格式是;expires=date-in-GMTString-format;
- max-age:设置过期的秒钟,;max-age=max-age-in-seconds (例如一年为606024*365);
- 我们也可以通过设置domain来设置cookie的作用域,例如domain=example.com,这样就会设置为example.com的子域也可以访问到这个cookie
- 我们也可以通过设置path来设置cookie的路径,例如path=/,这样就会设置为根路径下的所有页面都可以访问到这个cookie
- 我们也可以通过设置secure来设置cookie的安全性,例如secure=true,这样就会设置为只有https协议才可以访问到这个cookie
- 我们也可以通过设置httponly来设置cookie的安全性,例如httponly=true,这样就会设置为只有http协议才可以访问到这个cookie
- 我们也可以通过设置samesite来设置cookie的安全性,例如samesite=strict,这样就会设置为只有同源的请求才可以访问到这个cookie
// 设置 Cookie(键值对 + 属性)
document.cookie = "username=John; expires=Fri, 31 Dec 2024 12:00:00 UTC; path=/";// 读取所有 Cookie
const cookies = document.cookie; // 返回 "cookie1=value; cookie2=value"// 删除 Cookie(设置过期时间为过去)/ 关闭会话时会自动删除
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
BOM
BOM(Browser Object Model)是指浏览器对象模型,它提供了与浏览器交互的接口和对象。BOM 主要包括以下几个部分:
- Window 对象:表示浏览器窗口,是最顶层的对象。
代表浏览器窗口本身,是 BOM 的顶层对象,其他组件(如 location、history)均为其子属性 - 包含大量的属性,localStorage、console、location、history、screenX、scrollX等等
- 包含大量的方法,alert、close、scrollTo、open等等;
- 包含大量的事件,focus、blur、load、hashchange等等;
- 包含从EventTarget继承过来的方法,addEventListener、removeEventListener、dispatchEvent方法
MDN-window: window
// 获取当前窗口的宽度和高度
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;// 1.常见的属性
console.log(window.screenX)
console.log(window.screenY)window.addEventListener("scroll", () => {console.log(window.scrollX, window.scrollY)
})console.log(window.outerHeight)
console.log(window.innerHeight)//2.常见的方法
const scrollBtn = document.querySelector("#scroll")
scrollBtn.onclick = function() {// 1.scrollTowindow.scrollTo({ top: 2000 })// 2.closewindow.close()// 3.openwindow.open("http://www.baidu.com", "_self")// 4.调整窗口大小window.resizeTo(800, 600); // 5.alertwindow.alert("hello")// 6.confirmconst result = window.confirm("你确定要删除吗?")if (result) {console.log("用户点击了确定") } // 7.promptconst name = window.prompt("请输入你的名字:", "张三")console.log(name)}// 3.常见的事件
window.onload = function() {console.log("window窗口加载完毕~")
}window.onfocus = function() {console.log("window窗口获取焦点~")
}window.onblur = function() {console.log("window窗口失去焦点~")
}const hashChangeBtn = document.querySelector("#hashchange")
hashChangeBtn.onclick = function() {location.hash = "aaaa"
}
window.onhashchange = function() {console.log("hash发生了改变")
}
- Navigator 对象:提供浏览器的信息,如用户代理、平台等。
// 获取浏览器的名称和版本
const browserName = navigator.appName;
const browserVersion = navigator.appVersion;// 获取用户代理字符串
const userAgent = navigator.userAgent;// 检查浏览器是否支持某个功能
const isGeolocationSupported = navigator.geolocation;// 检查浏览器是否支持某种媒体类型
const isVideoSupported = navigator.canPlayType("video/mp4");// 检查浏览器是否可以使用摄像头
const isCameraSupported = navigator.mediaDevices.getUserMedia({ video: true });
- Location 对象:表示当前页面的 URL 信息,如路径、查询参数等。
// 获取当前页面的 URL
const currentURL = location.href;// 获取当前页面的路径
const currentPath = location.pathname;// 获取当前页面的查询参数
const queryParams = location.search;
// 1.属性
// href: 当前window对应的超链接URL, 整个URL;
// protocol: 当前的协议;
// host: 主机地址;
// hostname: 主机地址(不带端口);
// port: 端口;
// pathname: 路径;
// search: 查询字符串;
// hash: 哈希值;
// username:URL中的username(很多浏览器已经禁用);ppassword:URL中的password(很多浏览器已经禁用)// 2.location有如下常用的方法:
// assign:赋值一个新的URL,并且跳转到该URL中;
// replace:打开一个新的URL,并且跳转到该URL中(不同的是不会在浏览记录中留下之前的记录);
// reload:重新加载页面,可以传入一个Boolean类型
// 几个方法
// location.assign("http://www.baidu.com")
// location.href = "http://www.baidu.com"// location.replace("http://www.baidu.com")
// location.reload(false)
- History 对象:表示浏览器的历史记录,允许访问和操作历史记录。
// 前进
history.forward();// 后退
history.back();// 前进或后退指定的步数
history.go(2); // 前进两步
history.go(-2); // 后退两步// 监听历史记录变化
window.onpopstate = function(event) {console.log("历史记录发生了变化");
};
//1.属性
// length:返回历史记录的长度;
// state:返回当前页面的状态对象;
// 2.方法
// back():返回上一页,等价于history.go(-1);
// forward():前进下一页,等价于history.go(1);
// go():加载历史中的某一页;
// pushState():打开一个指定的地址; // 跳转(不刷新网页)
// replaceState():打开一个新的地址,并且使用replace
- Screen 对象:提供关于用户屏幕的信息,如分辨率、颜色深度等。
// 获取屏幕的宽度和高度
const screenWidth = screen.width;
const screenHeight = screen.height;// 获取屏幕的颜色深度
const colorDepth = screen.colorDepth;// 获取屏幕的可用宽度和高度
const availableWidth = screen.availWidth;
const availableHeight = screen.availHeight;
// 获取屏幕的像素密度
const pixelRatio = window.devicePixelRatio;// 获取屏幕的方向
const orientation = screen.orientation.type;// 获取屏幕的设备像素比
const devicePixelRatio = window.devicePixelRatio;// 获取屏幕的像素比
const pixelRatio = window.devicePixelRatio;// 获取屏幕的可用宽度和高度
const availableWidth = screen.availWidth;
const availableHeight = screen.availHeight;
- 其他对象:如 XMLHttpRequest、XMLDocument 等,用于处理 XML 数据和网络请求。
BOM 提供了丰富的方法和属性,用于与浏览器进行交互,例如打开新窗口、导航、获取用户输入等。
DOM
DOM 是浏览器提供的一个接口,用于操作 HTML 文档的结构和内容。DOM 提供了一组对象和方法,用于访问和修改 HTML 文档的元素、属性和内容。
DOM 提供了以下几个主要的对象:
document.addEventListener("click", () => {console.log("document被点击")
})const divEl = document.querySelector("#box")
const spanEl = document.querySelector(".content")divEl.addEventListener("click", () => {console.log("div元素被点击")
})spanEl.addEventListener("click", () => {console.log("span元素被点击")
})
- Document 对象:表示整个 HTML 文档,是 DOM 的入口点。
// 常见的属性
console.log(document.body)
console.log(document.title)
document.title = "Hello World"console.log(document.head)
console.log(document.children[0])console.log(window.location)
console.log(document.location)
console.log(window.location === document.location)// 常见的方法
// 创建元素
const imageEl = document.createElement("img")
const imageEl2 = new HTMLImageElement()// <div id="box" class="abc sumu" age="18">
// <span name="title" class="content">span元素</span>
// <!-- 哈哈哈 -->
// <strong></strong>
// <a href="#"></a>
// </div>
// <div></div>// <h2 name="title">标题</h2>
// <button>切换标题</button>
// 获取元素
const divEl1 = document.getElementById("box")
const divEl2 = document.getElementsByTagName("div")
const divEl3 = document.getElementsByName("title")
const divEl4 = document.querySelector(".content")
const divEl5 = document.querySelectorAll(".content")
- Element 对象:表示 HTML 文档中的元素,可以通过 Document 对象获取。
const divEl = document.querySelector("#box")// 常见的属性
console.log(divEl.id)
console.log(divEl.tagName)
console.log(divEl.children)
console.log(divEl.className)
console.log(divEl.classList)
console.log(divEl.clientWidth)
console.log(divEl.clientHeight)
console.log(divEl.offsetLeft)
console.log(divEl.offsetTop)// 常见的方法
const value = divEl.getAttribute("age")
console.log(value)
divEl.setAttribute("height", 1.88)
- Node 对象:表示 HTML 文档中的节点,可以通过 Document 对象获取。
const divEl = document.querySelector("#box")
const spanEl = document.querySelector(".content")// 常见的属性
console.log(divEl.nodeName, spanEl.nodeName)
console.log(divEl.nodeType, spanEl.nodeType)
console.log(divEl.nodeValue, spanEl.nodeValue)// childNodes
const spanChildNodes = spanEl.childNodes
const textNode = spanChildNodes[0]
console.log(textNode.nodeValue)// 常见的方法
const strongEl = document.createElement("strong")
strongEl.textContent = "我是strong元素"
divEl.appendChild(strongEl)// 注意事项: document对象
document.body.appendChild(strongEl)
阻止冒泡 、阻止默认行为
- event.stopPropagation():阻止事件向父元素传播,但不影响默认行为,点击按钮时阻止父元素触发事件
document.getElementById("child").addEventListener("click", (e) => {e.stopPropagation(); // 阻止冒泡console.log("子元素事件触发");
});
- event.preventDefault()
取消浏览器默认行为(如阻止表单提交、链接跳转),但不阻止事件冒泡,阻止链接跳转
document.querySelector("a").addEventListener("click", (e) => {e.preventDefault(); // 阻止跳转console.log("链接点击被拦截");
});
- return false(有限制)
在 DOM0 级事件模型(如 onclick 属性)中可同时阻止冒泡和默认行为,在 addEventListener 中无效,仅适用于内联事件处理
document.getElementById("child").onclick = function (e) {e.preventDefault(); // 阻止跳转console.log("子元素事件触发");return false; // 阻止冒泡
}<a href="#" onclick="return false;">点击</a>