Javascript 在javascript中获取设备宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6850164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:28:08  来源:igfitidea点击:

Get the device width in javascript

javascriptcssmedia-queries

提问by Nicholas Evans

Is there a way to get the users device width, as opposed to viewport width, using javascript?

有没有办法使用javascript获取用户设备宽度,而不是视口宽度?

CSS media queries offer this, as I can say

正如我所说,CSS 媒体查询提供了这一点

@media screen and (max-width:640px) {
    /* ... */
}

and

@media screen and (max-device-width:960px) {
    /* ... */
}

This is useful if I'm targeting smartphones in landscape orientation. For example, on iOS a declaration of max-width:640pxwill target both landscape and portrait modes, even on an iPhone 4. This is not the case for Android, as far as I can tell, so using device-width in this instance successfully targets both orientations, without targeting desktop devices.

如果我的目标是横向的智能手机,这很有用。例如,在 iOS 上,声明 max-width:640px将同时针对横向和纵向模式,即使在 iPhone 4 上也是如此。据我所知,Android 并非如此,因此在此实例中使用 device-width 成功地针对两个方向,不针对桌面设备。

However, if I'm invoking a javascript binding based on device width, I appear to be limited to testing the viewport width, which means an extra test as in the following,

但是,如果我根据设备宽度调用 javascript 绑定,我似乎仅限于测试视口宽度,这意味着额外的测试如下,

if ($(window).width() <= 960 && $(window).height <= 640) { /* ... */ }

This doesn't seem elegant to me, given the hint that device width is available to css.

考虑到 css 可以使用设备宽度的提示,这对我来说似乎并不优雅。

回答by Bryan Rieger

You can get the device screen width via the screen.width property.
Sometimes it's also useful to use window.innerWidth (not typically found on mobile devices) instead of screen width when dealing with desktop browsers where the window size is often less than the device screen size.

您可以通过 screen.width 属性获取设备屏幕宽度。
有时,在处理窗口大小通常小于设备屏幕大小的桌面浏览器时,使用 window.innerWidth(通常不在移动设备上找到)而不是屏幕宽度也很有用。

Typically, when dealing with mobile devices AND desktop browsers I use the following:

通常,在处理移动设备和桌面浏览器时,我使用以下内容:

 var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;

回答by Nicholas Evans

One issue with Bryan Rieger's useful answer is that on high-density displays, Apple devices report screen.width in dips, while Android devices report it in physical pixels. (See http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html.) I suggest using if (window.matchMedia('(max-device-width: 960px)').matches) {}on browsers supporting matchMedia.

Bryan Rieger 的有用答案的一个问题是,在高密度显示器上,Apple 设备以倾角报告 screen.width,而 Android 设备以物理像素报告它。(请参阅http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html。)我建议if (window.matchMedia('(max-device-width: 960px)').matches) {}在支持 matchMedia 的浏览器上使用。

回答by RogerRoger

I just had this idea, so maybe it's shortsighted, but it seems to work well and might be the most consistent between your CSS and JS.

我刚刚有了这个想法,所以也许它是短视的,但它似乎运作良好,并且可能是您的 CSS 和 JS 之间最一致的。

In your CSS you set the max-width value for html based on the @media screen value:

在您的 CSS 中,您根据 @media 屏幕值设置 html 的 max-width 值:

@media screen and (max-width: 480px) and (orientation: portrait){

    html { 
        max-width: 480px;
    }

    ... more styles for max-width 480px screens go here

}

Then, using JS (probably via a framework like JQuery), you would just check the max-width value of the html tag:

然后,使用 JS(可能通过 JQuery 之类的框架),您只需检查 html 标签的 max-width 值:

maxwidth = $('html').css('max-width');

Now you can use this value to make conditional changes:

现在您可以使用此值进行条件更改:

If (maxwidth == '480px') { do something }

If putting the max-width value on the html tag seems scary, then maybe you can put on a different tag, one that is only used for this purpose. For my purpose the html tag works fine and doesn't affect my markup.

如果在 html 标签上放置 max-width 值看起来很可怕,那么也许您可以放置​​一个不同的标签,一个仅用于此目的的标签。出于我的目的,html 标签工作正常,不会影响我的标记。



Useful if you are using Sass, etc: To return a more abstract value, such as breakpoint name, instead of px value you can do something like:

如果您使用 Sass 等,则很有用:要返回更抽象的值,例如断点名称,而不是 px 值,您可以执行以下操作:

  1. Create an element that will store the breakpoint name, e.g. <div id="breakpoint-indicator" />
  2. Using css media queries change the content property for this element, e. g. "large" or "mobile", etc (same basic media query approach as above, but setting css 'content' property instead of 'max-width').
  3. Get the css content property value using js or jquery (jquery e.g. $('#breakpoint-indicator').css('content');), which returns "large", or "mobile", etc depending on what the content property is set to by the media query.
  4. Act on the current value.
  1. 创建一个将存储断点名称的元素,例如 <div id="breakpoint-indicator" />
  2. 使用 css 媒体查询更改此元素的内容属性,例如“大”或“移动”等(与上述基本媒体查询方法相同,但设置 css 'content' 属性而不是 'max-width')。
  3. 使用 js 或 jquery (jquery eg $('#breakpoint-indicator').css('content');)获取 css 内容属性值,它返回“大”或“移动”等,具体取决于媒体查询设置的内容属性。
  4. 对当前值采取行动。

Now you can act on same breakpoint names as you do in sass, e.g. sass: @include respond-to(xs), and js if ($breakpoint = "xs) {}.

现在您可以像在 sass 中一样处理相同的断点名称,例如 sass:@include respond-to(xs)和 js if ($breakpoint = "xs) {}

What I especially like about this is that I can define my breakpoint names all in css and in one place (likely a variables scss document) and my js can act on them independently.

我特别喜欢这一点的是,我可以在 css 和一个地方(可能是变量 scss 文档)中定义我的断点名称,并且我的 js 可以独立地对它们进行操作。

回答by ZNS

var width = Math.max(window.screen.width, window.innerWidth);

var width = Math.max(window.screen.width, window.innerWidth);

This should handle most scenarios.

这应该可以处理大多数情况。

回答by Reundo

you can easily use

您可以轻松使用

document.documentElement.clientWidth

document.documentElement.clientWidth

回答by maxime schoeni

I think using window.devicePixelRatiois more elegant than the window.matchMediasolution:

我认为使用window.devicePixelRatiowindow.matchMedia解决方案更优雅:

if (window.innerWidth*window.devicePixelRatio <= 960 
    && window.innerHeight*window.devicePixelRatio <= 640) { 
    ... 
}

回答by MEAbid

check it

核实

const mq = window.matchMedia( "(min-width: 500px)" );

if (mq.matches) {
  // window width is at least 500px
} else {
  // window width is less than 500px
}

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

回答by Munawwar

Lumia phones give wrong screen.width (at least on emulator). So maybe Math.min(window.innerWidth || Infinity, screen.width)will work on all devices?

Lumia 手机给出错误的 screen.width(至少在模拟器上)。那么也许Math.min(window.innerWidth || Infinity, screen.width)适用于所有设备?

Or something crazier:

或者更疯狂的东西:

for (var i = 100; !window.matchMedia('(max-device-width: ' + i + 'px)').matches; i++) {}
var deviceWidth = i;

回答by FooBar

You should use

你应该使用

document.documentElement.clientWidth

It is regarded as cross-browser compability, and is the same method that jQuery(window).width(); uses.

算是跨浏览器兼容,和jQuery(window).width();方法一样。使用。

For detailed information have a look at: https://ryanve.com/lab/dimensions/

有关详细信息,查看:https: //ryanve.com/lab/dimensions/

回答by Abhishek Divekar

Just as an FYI, there is a library called breakpointswhich detects the max-width as set in CSS and allows you to use it in JS if-else conditions using <=, <, >, >= and == signs. I found it quite useful. The payload size is under 3 KB.

仅供参考,有一个名为breakpoints的库,它检测 CSS 中设置的最大宽度,并允许您使用 <=、<、>、>= 和 == 符号在 JS if-else 条件中使用它。我发现它很有用。有效载荷大小低于 3 KB。