Window 对象是浏览器中 JavaScript 的全局对象,代表浏览器窗口。它是 JavaScript 环境的顶层对象,所有全局变量和函数都是它的属性和方法。在浏览器中,Window 对象同时也是 Document 对象的宿主,提供了操作浏览器窗口的各种功能。
setTimeout
和 setInterval
等定时器方法。alert
、confirm
和 prompt
等交互方法。localStorage
和 sessionStorage
提供数据存储功能。// 直接使用全局变量
console.log(window);
// 省略 window 前缀
console.log(document); // 等价于 window.document
console.log(setTimeout); // 等价于 window.setTimeout
console.log(window.innerWidth); // 窗口内部宽度(像素)
console.log(window.innerHeight); // 窗口内部高度(像素)
console.log(window.outerWidth); // 窗口外部宽度(包括边框)
console.log(window.outerHeight); // 窗口外部高度(包括边框)
console.log(window.scrollX); // 水平滚动位置
console.log(window.scrollY); // 垂直滚动位置
console.log(window.location); // 当前 URL 信息
console.log(window.history); // 浏览器历史记录对象
console.log(window.history.length); // 历史记录条目数量
console.log(window.navigator); // 浏览器信息
console.log(window.screen); // 屏幕信息
console.log(window.screen.width); // 屏幕宽度
console.log(window.screen.height); // 屏幕高度
// 全局变量是 window 的属性
var globalVar = 42;
console.log(window.globalVar); // 42
// 全局函数是 window 的方法
function greet() {
return "Hello!";
}
console.log(window.greet()); // "Hello!"
// 打开新窗口
const newWindow = window.open('https://example.com', '_blank', 'width=500,height=400');
// 控制新窗口
if (newWindow) {
newWindow.focus();
// 可以通过 newWindow.document 访问新窗口的文档
}
// 关闭当前窗口(需要由脚本打开的窗口才能可靠关闭)
window.close();
// 检查窗口是否关闭
if (newWindow && !newWindow.closed) {
newWindow.close();
}
// 调整窗口大小
window.resizeTo(800, 600);
// 移动窗口位置
window.moveTo(100, 100);
// 滚动窗口
window.scrollTo(0, 500); // 滚动到垂直位置 500px
window.scrollBy(0, 100); // 向下滚动 100px
// 延迟执行函数
const timeoutId = setTimeout(() => {
console.log('3秒后执行');
}, 3000);
// 取消定时器
clearTimeout(timeoutId);
// 每隔一段时间执行函数
const intervalId = setInterval(() => {
console.log('每秒执行一次');
}, 1000);
// 停止定时器
clearInterval(intervalId);
// 优化动画性能
function animate() {
// 更新动画
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
alert('这是一个警告消息');
const isConfirmed = confirm('确定要执行此操作吗?');
if (isConfirmed) {
console.log('用户点击了确定');
} else {
console.log('用户点击了取消');
}
const userName = prompt('请输入您的姓名:', '');
if (userName) {
console.log('用户姓名:', userName);
}
// 存储数据
localStorage.setItem('theme', 'dark');
// 获取数据
const theme = localStorage.getItem('theme');
console.log('当前主题:', theme);
// 删除数据
localStorage.removeItem('theme');
// 清空所有数据
localStorage.clear();
// 存储数据(会话结束后清除)
sessionStorage.setItem('user', 'John');
// 获取数据
const user = sessionStorage.getItem('user');
console.log('当前用户:', user);
// 设置 cookie
document.cookie = 'username=John; expires=Thu, 31 Dec 2025 23:59:59 GMT; path=/';
// 获取 cookie
function getCookie(name) {
const cookies = document.cookie.split('; ');
for (const cookie of cookies) {
const [cookieName, cookieValue] = cookie.split('=');
if (cookieName === name) {
return cookieValue;
}
}
return null;
}
console.log('用户名:', getCookie('username'));
// DOM 加载完成
window.addEventListener('DOMContentLoaded', () => {
console.log('DOM 已加载');
});
// 页面完全加载(包括图片等资源)
window.addEventListener('load', () => {
console.log('页面已完全加载');
});
// 页面即将卸载
window.addEventListener('beforeunload', (event) => {
// 取消事件
event.preventDefault();
// Chrome 需要设置 returnValue
event.returnValue = '';
// 显示确认对话框
return '确定要离开此页面吗?';
});
window.addEventListener('resize', () => {
console.log('窗口大小已调整:', window.innerWidth, window.innerHeight);
});
window.addEventListener('scroll', () => {
console.log('滚动位置:', window.scrollY);
// 实现滚动时的导航栏效果
const navbar = document.getElementById('navbar');
if (window.scrollY > 100) {
navbar.classList.add('scrolled');
} else {
navbar.classList.remove('scrolled');
}
});
// 测量代码执行时间
console.time('operation');
// 执行一些操作
console.timeEnd('operation');
// 使用 Performance API
const start = performance.now();
// 执行一些操作
const end = performance.now();
console.log('操作耗时:', end - start, '毫秒');
// 创建大型数组
let largeArray = new Array(1000000).fill(0);
// 释放引用以允许垃圾回收
largeArray = null;
// 在主窗口中
const popup = window.open('popup.html', 'popup', 'width=400,height=300');
// 在弹出窗口中访问主窗口
const mainWindow = window.opener;
// 主窗口向弹出窗口发送消息
if (popup && !popup.closed) {
popup.postMessage('Hello from main window!', '*');
}
// 弹出窗口接收消息
window.addEventListener('message', (event) => {
console.log('收到消息:', event.data);
});
// 发送消息
const targetWindow = document.getElementById('iframe').contentWindow;
targetWindow.postMessage('Hello from parent!', 'https://example.com');
// 接收消息
window.addEventListener('message', (event) => {
if (event.origin === 'https://example.com') {
console.log('安全的消息:', event.data);
}
});
// 后退一步
window.history.back();
// 前进一步
window.history.forward();
// 跳转到历史记录中的某个位置
window.history.go(-2); // 后退两步
// 添加新的历史记录条目
window.history.pushState({ page: 'home' }, 'Home Page', '/home');
// 修改当前历史记录条目
window.history.replaceState({ page: 'about' }, 'About Page', '/about');
// 监听历史记录变化
window.addEventListener('popstate', (event) => {
console.log('历史记录变化:', event.state);
});
console.log('屏幕宽度:', window.screen.width);
console.log('屏幕高度:', window.screen.height);
console.log('可用宽度:', window.screen.availWidth);
console.log('可用高度:', window.screen.availHeight);
console.log('颜色深度:', window.screen.colorDepth);
console.log('设备像素比:', window.devicePixelRatio);
// 用于高分辨率屏幕的图像优化
if (window.devicePixelRatio > 1) {
// 使用高分辨率图像
}
// 使用 postMessage 进行安全通信
window.addEventListener('message', (event) => {
if (event.origin !== 'https://trusted-domain.com') {
return; // 拒绝来自不可信源的消息
}
console.log('安全消息:', event.data);
});
const audio = new Audio('sound.mp3');
audio.play();
// 请求媒体设备
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then((stream) => {
const videoElement = document.getElementById('video');
videoElement.srcObject = stream;
})
.catch((error) => {
console.error('访问媒体设备失败:', error);
});
// 在 React 组件中使用 window 对象
import React, { useEffect } from 'react';
function ScrollComponent() {
useEffect(() => {
const handleScroll = () => {
console.log('滚动位置:', window.scrollY);
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return <div>滚动监听组件</div>;
}
// 在 Vue 组件中使用 window 对象
export default {
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
console.log('窗口大小变化:', window.innerWidth);
}
}
};
// 不好的做法
var globalVar = 42;
// 更好的做法
const myModule = {
var: 42,
doSomething() { /* ... */ }
};
Window 对象是浏览器中 JavaScript 的核心,提供了丰富的功能来操作浏览器窗口、处理事件、管理存储和实现跨窗口通信。掌握 Window 对象的使用对于开发高质量、交互性强的 Web 应用至关重要。