[英]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.