现在的位置: 首页 > 综合 > 正文

javascript关闭窗口(兼容firefox,IE)

2018年05月15日 ⁄ 综合 ⁄ 共 2052字 ⁄ 字号 评论关闭

javascript关闭窗口,可以用下面简单的代码:

<a href="javascript:self.close()">关闭窗口</a>

我在IE7下测试通过,但是firefox3.0却不行。
难道firefox不支持在href中直接写JavaScript?于是改成下面的样子:

<a href="javascript:alert('Hello World')">弹出窗口</a>

这次IE7和firefox下测试都通过。那就不是href中直接写JavaScript的原因了。
继续测试firefox怎么关闭自身窗口

改成了如下代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
<!--
    function windowClose(){
        //self.close();
        window.close();
    }
//-->
</script>
<title>js测试</title>
</head>
<a href="javascript:self.close()">关闭窗口</a><br />
<a href="javascript:alert('Hello World')">弹出窗口</a><br />
<a href="#" onclick="windowClose()">js函数关闭窗口</a>
<body>
</body>
</html>

还是不能关闭窗口。难道firefox不支持window的close属性?
那window对象的close方法能不能关闭open方法打开的窗口呢?

写下面两个html文件放在同一个文件夹下

1.open.html

<script type="text/javascript">
<!--
    function openWindow(){
        window.open("new.html","newWindow","width=200,height=100,toolbar=no");
    }
//-->
</script>
<a href="#" onclick="openWindow()">open函数打开新窗口</a><br />
<a href="new.html" target="_blank">超级链接在新窗口中打开新页面</a><br />
<a href="new.html" target="_parent">超级链接在父窗口中打开新页面</a>

2.new.html

<a href="javascript:window.close()">关闭窗口</a>
<a href="javascript:self.close()">关闭窗口</a>

用open方法和在"_blank"打开的可以在新窗口中关闭,而在"_parent"中打开的在firefox中还是关闭不

因此在firefox里用window的close方法时要注意他和IE不同的地方:在父窗口打开的页面是不能用close

方法关闭的。

然后去google搜了一下:之所以window.close在firefox不能使用,是因为firefox默认不能关闭用户打

开的网页,我们可以这样设置firefox:

打开firefox,在地址栏输入about:config

找到dom.allow_scripts_to_close_windows这项并改为true。

现在知道为什么了吧。那篇文章还有一段不错的内容,摘录如下:

众所周知,在javascript中window.close()是用来关闭窗口的,而且ie和firefox都是支持的。为了实现

用户对浏览器的绝对控制,ie中用close关闭非open打开的窗口时会弹出一个对话框询问用户。有时候我

们不希望再这样哆嗦,但是怎么去掉这个框呢,用下面的代码就可以了

<script   language="javascript"   type="text/javascript"> 
  
  function   closeWindow()   { 
  
  window.open('','_parent',''); 
  
  window.close(); 
  
  } 
  
  </script>   
  <a   href="javascript:closeWindow();">Close   Window</a>

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wasw100/archive/2009/01/31/3855616.aspx

抱歉!评论已关闭.