【发布时间】:2012-10-08 01:00:41
【问题描述】:
有没有办法让链接在不使用 javascript 的情况下打开一个新的浏览器窗口(不是选项卡)?
【问题讨论】:
标签: html
有没有办法让链接在不使用 javascript 的情况下打开一个新的浏览器窗口(不是选项卡)?
【问题讨论】:
标签: html
使用纯 HTML 你无法影响这一点 - 每个现代浏览器(= 用户)都可以完全控制这种行为,因为它在过去被大量滥用......
您可以打开一个新窗口 (HTML4) 或一个新的浏览上下文 (HTML5)。现代浏览器中的浏览上下文主要是“新标签”而不是“新窗口”。您对此没有影响,也不能“强制”现代浏览器打开一个新窗口。
为此,请使用anchor element 的属性target[1]。您要查找的值是_blank[2]。
<a href="www.example.com/example.html" target="_blank">link text</a>
可以通过 javascript 强制创建一个新窗口 - 请参阅 Ievgen's excellent answer below 了解 javascript 解决方案。
(!) 但是,请注意,通过 javascript 打开窗口(如果未在锚元素的 onclick 事件中完成)会被弹出窗口阻止程序阻止!
[1] 这个属性可以追溯到浏览器没有选项卡并且使用框架集是最先进的时代。同时,该属性的功能略有改变(见MDN Docu)
[2] 还有一些其他值不再有意义(因为它们在设计时考虑了框架集),例如 _parent、_self 或 _top。
【讨论】:
你可以试试这个:-
<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>
【讨论】:
这将打开一个新窗口,而不是选项卡(使用 JavaScript,但非常简洁):
<a href="print.html"
onclick="window.open('print.html',
'newwindow',
'width=300,height=250');
return false;"
>Print</a>
【讨论】:
<a href="javascript:window.open('print.html', 'newwindow', 'width=300,height=250')">Print</a>
onclick="window.open(this.href,'newwindow','width=1000,height=800'); return false;" 这使用元素 <a> 的 href
我知道它有点旧 Q,但是如果你通过搜索解决方案到达这里,那么我通过 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">
编辑:
第一,我对原始代码做了一些小改动,现在它完全按照用户屏幕比例打开新窗口(适用于横向桌面)
但是,如果您使用 mobile,我建议您使用以下代码在新选项卡中打开链接(感谢 zvona answer in other question):
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;
}
【讨论】:
top=300, left=350 谢谢你的这行! :)