1.alert()
: 显示一个对话框,带有一段消息和确定按钮。
window.alert("Hello, World!");
2.confirm()
: 显示一个对话框,带有一段消息和两个按钮(确定和取消)。
var result = window.confirm("Are you sure?");
if (result) {
console.log("You clicked OK!");
} else {
console.log("You clicked Cancel!");
}
3.prompt()
: 显示一个对话框,带有一段消息和输入框
var result = window.prompt("Please enter your name:", "Harry Potter");
if (result !== null) {
console.log("Hello, " + result + "!");
}
4.open()
: 打开一个新的浏览器窗口或标签页。
window.open('https://www.example.com', '_blank');
5.close()
: 关闭当前窗口。注意,出于安全原因,这个函数通常只能关闭由脚本打开的窗口。
window.close();
6.print()
: 打印文档。
window.print();
7. focus()
: 将焦点设置到当前窗口。
window.focus();
8.blur()
: 移除当前窗口的焦点。
window.blur();
9. scrollTo()
: 滚动到文档中的特定位置。
window.scrollTo(0, 0); // 滚动到页面顶部
10.scrollBy()
: 相对于当前位置滚动文档。
window.scrollBy(0, 500); // 向下滚动500像素
11. setTimeout()
: 设置一个定时器,当定时器到期时执行函数。
setTimeout(function() {
console.log("This message is shown after 3 seconds");
}, 3000);
12.clearTimeout()
: 取消由 setTimeout()
设置的定时器。
var timerId = setTimeout(function() {
console.log("This won't be shown");
}, 3000);
clearTimeout(timerId);
13.setInterval()
: 设置一个定时器,按照指定的时间间隔周期性地执行函数。
setInterval(function() {
console.log("This message is shown every 2 seconds");
}, 2000);
14.clearInterval()
: 取消由 setInterval()
设置的定时器。
var intervalId = setInterval(function() {
console.log("This won't be shown anymore");
}, 2000);
clearInterval(intervalId);
15.addEventListener()
: 给 window
对象添加事件监听器。
window.addEventListener('resize', function() {
console.log("Window has been resized");
});
16. removeEventListener()
: 从 window
对象移除事件监听器。
window.removeEventListener('resize', someFunction);