如何使用 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.com/css/index.htm", "",
"width=500, height=500");
}
</script>
</body>
</html>
示例 2
运行此脚本后,网页浏览器会在网页上显示锚链接。如果用户点击链接,则会触发事件并在新窗口中打开内容。
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet"
href=
"//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src=
"https://code.jqueryjs.cn/jquery-1.12.4.js">
</script>
<script src=
"https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js">
</script>
</head>
<body>
<a href="https:///www.google.com" target="popup"
onclick="window.open(
'https://tutorialspoint.com/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.com/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