迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中获取浏览器宽度

作者:迹忆客 最近更新:2024/03/22 浏览次数:

浏览器宽度以像素为单位显示浏览器窗口的实际宽度。浏览器宽度与屏幕宽度不同。

它显示了可查看浏览器空间中的像素数,屏幕宽度是屏幕的总大小(以像素为单位)。


JavaScript 中在浏览器控制台中使用一行代码获取宽度

首先,打开浏览器控制台并将以下代码复制粘贴到浏览器控制台中。

浏览器的宽度总是小于或等于屏幕的宽度,因为它不包括滚动条和边框。

'Browser width: ' + window.innerWidth +
    ' pixels\nScreen width: ' + screen.width + ' pixels';

输出:

'Browser width: 982 pixels\nScreen width: 1536 pixels'


在 JavaScript 中使用 inner.widthinner.height 获取浏览器宽度和高度

我们将创建一个 HTML 页面,在其中我们将在代码主体内编写脚本。

在脚本部分,我们将编写一段代码,在输出中显示浏览器的内部宽度。

当我们运行 HTML 代码时,会在浏览器中打开一个页面。我们在脚本中使用 alert 方法在页面上显示消息。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Browser width</title>
    <h1>Getting width in HTML page</h1>
</head>
<body>
    <p id="demo"></p>
    <script>
        var w = window.innerWidth
        || document.documentElement.clientWidth
        || document.body.clientWidth;
        var h = window.innerHeight
        || document.documentElement.clientHeight
        || document.body.clientHeight;
        var x = document.getElementById("demo");
        x.innerHTML = "Your Browser inner window width: " + w + ", height: " + h + ".";
        alert("Your Browser inner window width: " + w + ", height: " + h + ".");
        </script>
</body>
</html>

显示消息将显示浏览器的内部宽度和高度。在这种情况下,宽度和高度是默认值。

但是当我们改变浏览器的宽度时。显示消息将显示浏览器的不同宽度和高度。

输出:

Your Browser inner window width: 362, height: 450.

inner.width 为我们提供了浏览器的内部宽度。inner.height 为我们提供了浏览器的内部高度。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:https://www.jiyik.com/tm/xwzj/web_9118.html

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便