给定一个在设备上运行的 html 文档, 如何使用 JavaScript 查找屏幕设备的宽度? 下面本篇文章就来给大家介绍一下使用 JavaScript 获取设备屏幕宽度的方法, 希望对大家有所帮助.
方法一: 使用 Windows.innerWidth 获取设备屏幕的宽度
innerWidth 属性用于返回设备的宽度, 以像素计.
示例:
- <!DOCTYPE HTML>
- <HTML>
- <head>
- <meta charset="UTF-8">
- <title>
- 如何获取 JavaScript 中的设备屏幕宽度?
- </title>
- </head>
- <body style="text-align:center;">
- <h1 style="color:green;">
- 获取 JavaScript 中的设备屏幕宽度:
- </h1>
- <p id="UP" style="font-size: 19px; font-weight: bold;">
- </p>
- <button onclick="Fun()">
- 单击此处
- </button>
- <p id="DOWN" style="color: green; font-size: 24px; font-weight: bold;">
- </p>
- <!-- Script to display the device screen width -->
- <script>
- var el_up = document.getElementById("UP");
- var el_down = document.getElementById("DOWN");
- el_up.innerHTML = "单击按钮, 以获取设备屏幕的宽度";
- function Fun() {
- var width = Windows.innerWidth;
- el_down.innerHTML = width + "像素";
- }
- </script>
- </body>
- </HTML>
效果图:
方法二: 使用 document.documentElement.clientWidth 方法获取设备屏幕的宽度
document.documentElement.clientWidth 方法拥有获取浏览器窗口文档显示区域的宽度, 不包括滚动条.
示例:
- <!DOCTYPE HTML>
- <HTML>
- <head>
- <meta charset="UTF-8">
- <title>
- 如何获取 JavaScript 中的设备屏幕宽度?
- </title>
- </head>
- <body style="text-align:center;">
- <h1 style="color:green;">
- 获取 JavaScript 中的设备屏幕宽度:
- </h1>
- <p id="UP" style="font-size: 19px; font-weight: bold;">
- </p>
- <button onclick="Fun()">
- 单击此处
- </button>
- <p id="DOWN" style="color: green; font-size: 24px; font-weight: bold;">
- </p>
- <!-- Script to display the device screen width -->
- <script>
- var el_up = document.getElementById("UP");
- var el_down = document.getElementById("DOWN");
- el_up.innerHTML = "单击按钮, 以获取设备屏幕的宽度";
- function Fun() {
- el_down.innerHTML = document.documentElement.clientWidth + "像素";
- }
- </script>
- </body>
- </HTML>
效果图:
来源: http://www.css88.com/qa/javascript/10317.html