简体   繁体   中英

Basic Javascript question: How to open a new window?

How do I open a new window in javascript properly?

I've tried:

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

This causes a new window to pop up but in Firefox it leaves the original page with a blank window saying "[object Window]". I've also had issues with IE as well.

How can I open a window that works in Firefox, IE, Safari and Chrome?

Bonus: If you can help in creating a link that is javascript degradable (I think that's the term).

javascript: links are pretty old-school. Try it with an onclick attribute. And don't forget to return false in the onclick handler to prevent the main page from following the link too.

<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>

By putting the script in the href property, the link will follow the string representation of the return value of the script.

The most backwards compatible way is to put the url and target in the link as regular attributes, and use the onclick event to open a window instead of following the link. By returning false from the event you prevent the link from being followed:

<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>

If Javascript is disabled in the browser, it will follow the link instead and open it in a new window.

Use the target _blank to open a new window.

您可以在JavaScript代码中添加void(0) ,这将阻止浏览器对当前窗口执行任何操作

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

Or make it a function:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM