如何使用 JavaScript 将弹出窗口居中显示在屏幕上?
在本教程中,我们将学习如何使用 JavaScript 将弹出窗口居中显示在屏幕上。程序员经常需要打开一个新的弹出窗口来显示另一个网页,而无需将用户重定向到另一个网页。在这种情况下,开发人员使用window.open()方法打开新的浏览器窗口。
此外,我们还可以设置弹出窗口的样式并设置高度和宽度。此外,我们还可以更改弹出窗口的位置以使其看起来更好。
弹出窗口示例
在本节中,我们将创建一个弹出窗口示例,以熟悉window.open()方法的工作原理。此外,我们将学习如何设置window.open()方法的属性以使其更完善。
语法
用户可以按照以下语法使用 window.open() 方法。
newWindow = window.open(url, 'popUpWindow', 'height=' + height + ', width=' + width + ', resizable=yes, scrollbars=yes, toolbar=yes');
参数
URL − 它是网页的 URL,将在浏览器的弹出窗口中打开。
高度 − 它设置弹出窗口的高度。
宽度 − 它设置弹出窗口的宽度。
可调整大小 − 它允许调整弹出窗口的大小。
滚动条 − 如果窗口内的内容大于窗口大小,它将在弹出窗口内显示滚动条。
示例
在下面的示例中,我们创建了一个按钮。当用户单击按钮时,它将调用名为openPopUp()的函数。在openPopUp()函数中,我们实现了window.open()方法,该方法在新的窗口中打开 TutorialsPoint 网站的主页。
<html> <head> </head> <body> <h2> Center the popup window using the JavaScript. </h2> <h4> Click the button to open popup window at top left corner. </h4> <button style=" height : 30px; width: 200px; " onclick = "openPopUp()"> click to open popup </button> <script> // function to open the popup window function openPopUp() { let url = "https://tutorialspoint.com/index.htm"; let height = 600; let width = 1200; newWindow = window.open( url, 'popUpWindow', 'height=' + height + ', width=' + width + ', resizable=yes,scrollbars=yes,toolbar=yes' ); } </script> </body> </html>
在上面的输出中,当用户单击按钮时,它将在左上角打开弹出窗口。
将弹出窗口居中
我们已经了解了有关弹出窗口的基本知识。现在,我们将以这样的方式设置属性,以便用户可以在屏幕中央看到弹出窗口。默认情况下,弹出窗口出现在屏幕的左上角。
我们将设置弹出窗口的左侧和顶部位置,这将使其出现在中心。
语法
用户可以按照以下语法使用window.open()方法,将左侧和顶部属性添加到其中。
// set the horizontal center of the popup window the center of the screen. var left = ( screen.width– width_of_popup_window ) / 2; // set thevertical center of the popup window the center of the screen. var top = ( screen.height -height_of_popup_window ) / 2; var newWindow = window.open( url, "center window", 'resizable=yes, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
参数
在上述方法中,我们添加了两个新参数
左侧 − 它设置窗口的起始左侧位置。
顶部 − 它设置弹出窗口的起始顶部位置。
Screen.width − 它以像素为单位返回屏幕宽度。
Screen.height − 它以像素为单位返回屏幕高度。
示例
在下面的示例中,我们向 window.open() 方法添加了左侧和顶部属性,并提供适当的值以使弹出窗口居中。
<html> <head> </head> <body> <h2> Center the popup window using the JavaScript. </h2> <h4> Click the button to open popup window at center. </h4> <button style = " height:30px; width:200px; " onclick = "openPopUp()"> click to open popup </button> <script> // function to open the popup window function openPopUp() { let url = "https://tutorialspoint.com/index.htm"; let height = 300; let width = 700; var left = ( screen.width - width ) / 2; var top = ( screen.height - height ) / 2; var newWindow = window.open( url, "center window", 'resizable = yes, width=' + width + ', height=' + height + ', top='+ top + ', left=' + left); } </script> </body> </html>
当用户单击按钮打开弹出窗口时,它将出现在设备屏幕的中间。
我们已经学习了如何仅使用 JavaScript 将弹出窗口居中。这非常简单,我们只需要向 window.open() 方法添加左侧和顶部属性即可。此外,我们还可以向 window.open() 方法添加许多其他属性以使其更具功能性。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP