如何使用 JavaScript 在新視窗中開啟連結?
如果您希望使用者點選連結並在新視窗中開啟這些連結,因為您希望使用者在檢視連結內容時仍停留在您的網站上。那麼您需要使用此解決方案。
透過使用 JavaScript,您可以輕鬆地配置所有連結,以便在單擊時在新視窗中開啟。
在新視窗中開啟連結的方法
使用 window.open() 方法
JavaScript 的 window.open() 方法允許您開啟一個新的瀏覽器視窗或標籤頁,並指定 URL。它可以用來開啟 HTML 文件、影像檔案、PDF 文件等。
根據函式呼叫中傳遞的引數,視窗將具有可自定義的功能,例如工具欄和捲軸。此方法還提供各種選項來控制視窗開啟時在螢幕上的顯示方式。
以下是在新視窗中開啟連結的示例
示例 1
在此示例中,我們將開啟一個具有定義視窗尺寸的新視窗。
<!DOCTYPE html>
<html>
<body style="text-align:center;">
<p>
Click Button To Open New Window
</p>
<button onclick="newwindow()">
Open
</button>
<script>
function newwindow() {
window.open("https://tutorialspoint.tw/css/index.htm", "",
"width=500, height=500");
}
</script>
</body>
</html>
示例 2
執行此指令碼後,網頁瀏覽器會在網頁上顯示錨鏈接。如果使用者點選連結,則會觸發事件並在新視窗中開啟內容。
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet"
href=
"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src=
"https://code.jquery.com/jquery-1.12.4.js">
</script>
<script src=
"https://code.jquery.com/ui/1.12.1/jquery-ui.js">
</script>
</head>
<body>
<a href="https:///www.google.com" target="popup"
onclick="window.open(
'https://tutorialspoint.tw/javascript/index.htm','popup',
'width=500,height=500'); return false;">
JavaScript Tutorial
</a>
</body>
</html>
示例 3
執行此指令碼後,瀏覽器會在網頁上顯示文字和按鈕。當用戶點選按鈕時,會觸發事件並在新視窗中開啟 URL,併為該 URL 指定一些說明。
<!DOCTYPE html>
<html>
<body>
<p>Click Button To Open New Window</p>
<button onclick="newwindow()">Click</button>
<script>
function newwindow() {
window.open("https://tutorialspoint.tw/javascript/index.htm",
"_blank","toolbar=no,scrollbars=no,resizable=yes,top=500,left=500,width=400,height=400");
}
</script>
</body>
</html>
示例 4
當指令碼執行時,它將生成一個輸出,其中包含網頁上的文字以及開啟和關閉按鈕。當用戶點選開啟按鈕時,會觸發一個事件開啟一個新視窗,如果使用者點選關閉按鈕,則關閉已開啟的視窗。
<!DOCTYPE html>
<html>
<body>
<h2>Click Open and Close</h2>
<button onclick="openWindow()">Open </button>
<button onclick="closeWindow()">Close </button>
<script>
let myWindow;
function openWindow() {
myWindow = window.open("", "", "width=500,height=300");
}
function closeWindow() {
myWindow.close();
}
</script>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP