2009-11-25 127 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>