要实现父窗口控制只弹出一个子窗口,需要满足以下几个步骤:
要实现父窗口控制只弹出一个子窗口,需要满足以下几个步骤:
-
在父窗口中定义一个全局变量,用于保存打开的子窗口对象。
-
在打开子窗口的函数中,先判断全局变量是否为空。如果为空,说明没有打开过子窗口,那么创建新的子窗口对象并赋值给全局变量。如果不为空,说明已经存在子窗口,那么判断子窗口是否关闭,如果关闭,则再次创建新的子窗口对象并赋值给全局变量;如果没有关闭,则聚焦在已存在的子窗口上。
-
在子窗口关闭时,将全局变量的值置为空。
下面是两个示例说明:
- 在父窗口点击按钮弹出子窗口
父窗口代码:
<script>
var childWindow = null;
function openChildWindow(url) {
if (childWindow && !childWindow.closed) {
childWindow.focus();
} else {
childWindow = window.open(url, "childWindow");
}
}
function closeChildWindow() {
if (childWindow && !childWindow.closed) {
childWindow.close();
childWindow = null;
}
}
</script>
<button onclick="openChildWindow('https://www.example.com')">打开子窗口</button>
<button onclick="closeChildWindow()">关闭子窗口</button>
子窗口代码:
<script>
window.onunload = function() {
window.opener.childWindow = null;
}
</script>
- 在子窗口点击链接打开新的子窗口
父窗口代码:
<script>
var childWindow = null;
function openChildWindow(url) {
if (childWindow && !childWindow.closed) {
childWindow.focus();
} else {
childWindow = window.open(url, "childWindow");
}
}
function closeChildWindow() {
if (childWindow && !childWindow.closed) {
childWindow.close();
childWindow = null;
}
}
</script>
<button onclick="openChildWindow('https://www.example.com')">打开子窗口</button>
<button onclick="closeChildWindow()">关闭子窗口</button>
子窗口代码:
<script>
window.onunload = function() {
if (opener && opener.childWindow && !opener.childWindow.closed) {
opener.childWindow.close();
}
}
</script>
<a href="https://www.example.com" target="_blank" onclick="window.open(this.href, 'childWindow'); return false;">点击打开新的子窗口</a>
织梦狗教程
本文标题为:用javascript父窗口控制只弹出一个子窗口


基础教程推荐
猜你喜欢
- CSS中margin边界叠加问题及解决方案 2023-12-29
- JavaScript中windows.open()、windows.close()方法详解 2023-11-30
- 关于二级域名下使用一级域名下的COOKIE的问题 2024-02-12
- CSS教程:vlink,alink,link和a:link 2024-01-24
- js禁止页面刷新与后退的方法 2023-12-21
- ajax三级联动的实现方法 2023-01-31
- networkInformation.downlink测用户网速方法详解 2023-12-20
- 详解如何较好的使用js 2023-12-21
- layui数据表格-通过点击按钮使数据表格中的字段值增加 2022-12-16
- JavaScript 判断浏览器类型及版本 2023-12-20