2009-11-25 128 views
0

如何正确打开JavaScript中的新窗口?基本的Javascript问题:如何打开一个新窗口?

我已经试过:

<a href='javascript:window.open("testing.html","mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0");' >New Window</a> 

这将导致一个新的窗口弹出但在Firefox它离开原来的页面与一个空白的窗口说:“[对象]窗口”。我也遇到了IE问题。

如何打开一个适用于Firefox,IE,Safari和Chrome的窗口?

奖励:如果你可以帮助创建一个javascript可降解的链接(我认为这是一个术语)。

回答

3

通过将脚本放入href属性中,链接将跟随返回的字符串表示形式脚本的价值。

最向后兼容的方法是将URL和目标放在链接中作为常规属性,并使用onclick事件打开一个窗口而不是链接。通过从事件返回false您阻止跟着链接:

<a href="testing.html" target="_blank" onclick="window.open(this.href,this.target,'menubar=0,resizable=1,width=200,height=500,left=0,top=0');return false;">New Window</a> 

如果JavaScript在浏览器中禁用,将按照链接,而不是在新窗口中打开它。

使用目标_blank打开一个新窗口。

+0

感谢您的优秀解释!你知道这是否适用于IE6? – chris 2009-11-25 05:07:14

+0

@chris:它绝对适用于IE6。我希望它至少可以在IE4上工作起来... – Guffa 2009-11-25 05:18:30

+0

@Guffa:很好,谢谢! – chris 2009-11-25 06:35:00

3

javascript:链接是相当古老的学校。尝试使用onclick属性。并且不要忘记onclick处理程序中的return false,以防止主页面跟随链接。

<a href="testing.html" onclick="window.open(this.href,'mywindow','menubar=0,resizable=1,width=200,height=500,left=0,top=0'); return false;">New Window</a> 
0

您可以添加void(0)到你的JavaScript代码,这将防止浏览器做任何事情到当前窗口

<a href='javascript:window.open("testing.html","mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0"); void(0)' >New Window</a> 
0
<a href='javascript:(function(){window.open("testing.html","mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0")}();' >New Window</a> 

或使其功能:

<a href="file.html" class="popup">File</a> 

<script>window.onload = function(){ 
document.getElementsByTagName('a').onclick = 
function(evt){ el = evt.target; if (el.className == 'popup'){ 
     window.open(el.href,"mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0"); 
     return false; }; };</script>