[英]How to open a link in a new window?
我正在尝试使用 HTML 和 JS 使用我的链接制作 window 弹出窗口。
到目前为止,我已经设法得到这个<a href="myLink" target="_blank" rel="noreferrer">myText</a>
,但这只是使链接在新选项卡中打开。
这是在新的 window 中打开链接的方法。
<a href="myLink"
target="popup"
onclick="window.open('myLink','popup','width=600,height=600'); return false;">
Open Link in Popup
</a>
永远记住有时用户配置他们的浏览器来阻止所有新标签和 windows(至少我是这样做的),以避免烦人的广告和点击诱饵链接。
任何打开新浏览器上下文而不指定尺寸的方法都将根据用户的偏好使用选项卡或 window。
一般来说,试图绕过这种偏好并不是一个好主意。 如果用户决定他们想要一个新的 window 中的标签,他们总是可以将它撕成一个。
也就是说,如果您指定尺寸,它将触发一个新的 window,如果浏览器完全支持它(例如,大多数移动设备根本不支持 windows)。
addEventListener("click", event => {
const target = event.target;
if (!target.classList.contains("force-window")) {
return;
}
const url = target.href;
const width = window.innerWidth;
const height = window.innerHeight;
const features = `width=${width},height=${height}`;
window.open(url, "_blank", features);
event.preventDefault();
});
<a href="myLink" target="_blank" rel="noreferrer" class="force-window">myText</a>
不幸的是,这将产生一个 window 缺少大部分预期功能。 请参阅window.open
文档将它们添加回来,但请注意(至少在 Chrome 中)添加菜单栏将导致高度和宽度被忽略并将内容放回新选项卡中。
作者控制的新 windows 很痛苦,几乎总是最好避免。 我不会碰它们,除非我需要做一些事情,比如在一个小的 window 中弹出一些内容(比如聊天或音乐播放器),当用户浏览网站时,它可以保留在屏幕上……即使这样,我通常也会倾向于而是写一个 SPA。
当您想使用给定的 url 打开一个弹出窗口时,您必须使用window.open()
function。
The windows.open()
accepts a few parameters called Window features, which you can find here https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Window_features , to define the popup. 当您传递它的宽度和高度时,它将在弹出窗口中打开。
<a id="url" href="https://www.google.com">myText</a>
<script>
document.getElementById("url").addEventListener('click', evt => {
evt.preventDefault();
let elem = document.getElementById("url");
let url = elem.getAttribute("href");
window.open(url, "popup", "width=700,height=700");
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.