各位浏览器指挥官们,准备好解锁JavaScript的超能力了吗?本章我们要学习如何与浏览器直接"对话",控制窗口、操作历史、获取设备信息... 这些技能让你从"网页写手"升级为"浏览器魔法师"!
11.1 window对象 - 浏览器世界的"上帝对象"
window
是BOM(浏览器对象模型)的顶级对象,就像浏览器宇宙的中心:
// 获取窗口尺寸
console.log(`窗口宽度:${window.innerWidth}px`);
console.log(`窗口高度:${window.innerHeight}px`);
// 导航到新页面
window.location.href = "https://www.example.com";
// 打开新窗口
let popup = window.open("popup.html", "广告", "width=300,height=200");
setTimeout(() => popup.close(), 3000); // 3秒后关闭
实用技巧 - 监听窗口变化:
window.addEventListener("resize", () => {
console.log(`窗口大小变为:${window.innerWidth}x${window.innerHeight}`);
});
window.addEventListener("scroll", () => {
if (window.scrollY > 100) {
document.querySelector(".back-to-top").style.display = "block";
}
});
11.2 location对象 - URL的"解剖专家"
location
对象让你可以"玩弄"URL于股掌之间:
console.log("当前URL:", location.href);
console.log("协议:", location.protocol); // https:
console.log("主机:", location.host); // www.example.com:8080
console.log("路径:", location.pathname); // /products/index.html
console.log("查询参数:", location.search); // ?id=123
// 修改URL但不刷新页面
history.pushState({}, "", "/new-page#section1");
// 重定向到新页面
function redirect(url) {
location.href = url;
// 或者 location.assign(url);
// 强制刷新:location.replace(url);
}
URL参数解析函数:
function getQueryParams() {
return Object.fromEntries(
new URLSearchParams(location.search).entries()
);
}
// 假设URL是 ?name=John&age=30
console.log(getQueryParams()); // {name: "John", age: "30"}
11.3 navigator对象 - 浏览器"身份证"
navigator
揭露了浏览器和设备的秘密信息:
console.log("浏览器信息:", navigator.userAgent);
console.log("语言:", navigator.language);
console.log("是否在线:", navigator.onLine);
console.log("CPU核心数:", navigator.hardwareConcurrency);
// 检测移动设备
function isMobile() {
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
}
// 获取地理位置
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(pos => {
console.log(`纬度:${pos.coords.latitude}`);
console.log(`经度:${pos.coords.longitude}`);
});
}
剪贴板API实战:
// 复制文本到剪贴板
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log("复制成功!");
} catch (err) {
console.error("复制失败:", err);
}
}
// 从剪贴板读取
async function pasteText() {
try {
const text = await navigator.clipboard.readText();
console.log("剪贴板内容:", text);
} catch (err) {
console.error("读取失败:", err);
}
}
11.4 定时器 - JavaScript的"闹钟"
定时器让你的代码学会"等待":
// 一次性定时器
let timeoutId = setTimeout(() => {
console.log("3秒后执行");
}, 3000);
// 取消执行
clearTimeout(timeoutId);
// 周期性定时器
let count = 0;
let intervalId = setInterval(() => {
console.log(`第${++count}次执行`);
if (count >= 5) clearInterval(intervalId);
}, 1000);
动画实战 - 进度条:
function animateProgressBar(duration) {
let start = null;
const bar = document.querySelector(".progress-bar");
function step(timestamp) {
if (!start) start = timestamp;
const progress = (timestamp - start) / duration;
bar.style.width = `${Math.min(progress * 100, 100)}%`;
if (progress < 1) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
}
animateProgressBar(3000); // 3秒动画
11.5 本地存储 - 浏览器的"小仓库"
告别Cookie,拥抱现代存储API:
localStorage - 长期存储
// 存储数据
localStorage.setItem("username", "John");
localStorage.setItem("theme", "dark");
// 读取数据
console.log(localStorage.getItem("username")); // "John"
// 删除数据
localStorage.removeItem("theme");
// 清空所有
// localStorage.clear();
// 存储对象
let user = {name: "John", age: 30};
localStorage.setItem("user", JSON.stringify(user));
let storedUser = JSON.parse(localStorage.getItem("user"));
sessionStorage - 会话级存储
// 用法同localStorage,但标签页关闭后数据消失
sessionStorage.setItem("tempData", "123");
购物车存储实战:
class Cart {
constructor() {
this.items = JSON.parse(localStorage.getItem("cart")) || [];
}
addItem(product) {
this.items.push(product);
this._save();
}
removeItem(id) {
this.items = this.items.filter(item => item.id !== id);
this._save();
}
_save() {
localStorage.setItem("cart", JSON.stringify(this.items));
}
get count() {
return this.items.length;
}
}
// 使用
const cart = new Cart();
cart.addItem({id: 1, name: "商品A", price: 100});
console.log(cart.count);
本章总结:
- window是浏览器环境的根对象
- location用于URL操作和页面导航
- navigator提供浏览器和设备信息
- 定时器控制代码执行时机
- 本地存储实现数据持久化
实战练习:
- 制作一个记住用户偏好的主题切换器
- 实现一个倒计时跳转页面功能
- 开发一个基于地理位置的城市天气显示组件
生活剧场:
// 浏览器指纹生成器
function getBrowserFingerprint() {
const fingerprint = {
userAgent: navigator.userAgent,
language: navigator.language,
screen: `${window.screen.width}x${window.screen.height}`,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
plugins: Array.from(navigator.plugins).map(p => p.name),
};
return JSON.stringify(fingerprint, null, 2);
}
// 页面离开提醒
window.addEventListener("beforeunload", (e) => {
if (document.querySelector("textarea").value) {
e.preventDefault();
e.returnValue = "你有未保存的内容,确定要离开吗?";
}
});
// 网络状态检测
window.addEventListener("online", () => {
console.log("网络已连接!");
document.querySelector(".offline-warning").style.display = "none";
});
window.addEventListener("offline", () => {
console.log("网络断开!");
document.querySelector(".offline-warning").style.display = "block";
});
下一章我们将探索ES6+的新特性,解锁现代JavaScript的超级语法糖!准备好升级你的代码装备了吗?