是否有一种方法可以在不使用JavaScript的情况下打开一个新的浏览器窗口而不是标签页?
这将会打开一个新窗口,而不是标签页(使用JavaScript实现,但非常简洁):
<a href="print.html"
onclick="window.open('print.html',
'newwindow',
'width=300,height=250');
return false;"
>Print</a>
使用纯HTML无法影响此行为 - 因为它曾经被滥用过,每个现代浏览器(用户)都对此行为有完全的控制权。
您可以打开一个新窗口(HTML4)或一个新浏览上下文(HTML5)。在现代浏览器中,浏览上下文通常是“新标签页”,而不是“新窗口”。您对此没有影响力,并且不能“强制”现代浏览器打开一个新窗口。
为了实现这一点,请使用锚元素的属性target
[1]。您要寻找的值是_blank
[2]。
<a href="www.example.com/example.html" target="_blank">link text</a>
通过 JavaScript 强制在新窗口打开是可能的 - 参见下面 Ievgen 的优秀答案 的 JavaScript 解决方案。
(!) 然而,需要注意的是,通过 JavaScript 打开新窗口(如果不是在锚元素的 onclick 事件中完成)可能会受到弹出窗口拦截器的阻止!
[1] 这个属性的历史可以追溯到浏览器没有标签页并且使用框架集技术是最先进的时候。与此同时,这个属性的功能略有变化(请参阅 MDN 文档)
[2] 还有一些其他的值,它们已经没有太多意义了(因为它们是基于框架集设计的),比如 _parent
、_self
或者 _top
。
我知道这是一个有些陈旧的问题,但如果您通过搜索解决方案来到这里,那么我可以使用jQuery提供一个不错的解决方案。
jQuery('a[target^="_new"]').click(function() {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
});
它将在新窗口中打开所有<a target="_new">
。
编辑:
首先,我对原始代码进行了一些小的更改,现在它可以完美地在用户屏幕比例下打开新窗口(适用于横向桌面)。
但是,我建议您使用以下代码,在移动设备上打开链接并在新标签页中显示(感谢zvona在其他问题中的回答):
jQuery('a[target^="_new"]').click(function() {
return openWindow(this.href);
}
function openWindow(url) {
if (window.innerWidth <= 640) {
// if width is smaller then 640px, create a temporary a elm that will open the link in new tab
var a = document.createElement('a');
a.setAttribute("href", url);
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
}
else {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
return false;
}
<a href="some.htm" target="_blank">Link Text</a>
你也可以尝试这个:
<a href="some.htm" onclick="if(!event.ctrlKey&&!window.opera){alert('Hold the Ctrl Key');return false;}else{return true;}" target="_blank">Link Text</a>
href
属性,以鼓励浏览器正确地为链接设置样式:请参见此处:http://jsfiddle.net/tobek/GPg6t/1/。`href`应该指向您正在使用JS打开的实际链接,这保持了语义正确性,并且更容易被搜索引擎理解。`return false`防止浏览器实际跳转到该链接。 - tobek<a href="javascript:window.open('print.html', 'newwindow', 'width=300,height=250')">打印</a>
。 - Maxwell s.conclick="window.open(this.href,'newwindow','width=1000,height=800'); return false;"
,这将使用<a>
元素的 href 属性。 - Koronos