实验 Window Open 和 Close 方法
在这一步中,你将探索 window.open()
和 window.close()
方法,这些方法允许你以编程方式创建和管理新的浏览器窗口或标签页。
导航到项目目录:
cd ~/project/bom-demo
首先,创建一个名为 popup.html
的新 HTML 文件:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Popup Window</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
}
</style>
</head>
<body>
<h1>This is a Popup Window</h1>
<p>Opened using window.open() method</p>
<button onclick="window.close()">Close Window</button>
</body>
</html>
现在,更新 bom-methods.js
文件以包含窗口操作方法:
// Function to open a new window
function openNewWindow() {
const outputDiv = document.getElementById("output");
// Open a new window with specific dimensions
const newWindow = window.open(
"popup.html",
"PopupWindow",
"width=400,height=300,resizable=yes"
);
// Check if window was successfully opened
if (newWindow) {
outputDiv.textContent = "New window opened successfully!";
} else {
outputDiv.textContent = "Popup blocked. Please allow popups.";
}
}
// Function to close the most recently opened window
function closeLastWindow() {
const outputDiv = document.getElementById("output");
try {
// Attempt to close the last opened window
const lastWindow = window.open("", "_blank");
if (lastWindow) {
lastWindow.close();
outputDiv.textContent = "Last opened window closed.";
} else {
outputDiv.textContent = "No window to close.";
}
} catch (error) {
outputDiv.textContent = "Error closing window.";
}
}
// Create buttons for window operations
function createWindowButtons() {
const openButton = document.createElement("button");
openButton.textContent = "Open New Window";
openButton.onclick = openNewWindow;
const closeButton = document.createElement("button");
closeButton.textContent = "Close Last Window";
closeButton.onclick = closeLastWindow;
document.body.appendChild(openButton);
document.body.appendChild(closeButton);
}
// Call the function to add buttons when page loads
createWindowButtons();
更新 index.html
文件以确保兼容性:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>BOM Methods Demonstration</title>
</head>
<body>
<h1>Browser Object Model (BOM) Methods</h1>
<div id="output"></div>
<script src="bom-methods.js"></script>
</body>
</html>
关于 window.open()
和 window.close()
的关键点:
window.open()
创建一个新的浏览器窗口或标签页
- 可以指定 URL、窗口名称和特性
window.close()
关闭当前或指定的窗口
- 弹出窗口拦截器可能会阻止窗口打开
当你在浏览器中打开 index.html
文件时:
- 点击 "Open New Window" 以创建一个新的弹出窗口
- 点击 "Close Last Window" 以关闭最近打开的窗口
- 输出 div 将显示窗口操作的状态