在javascript中获取设备宽度

发布于 2024-11-26 13:37:27 字数 650 浏览 2 评论 0原文

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

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

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

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

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

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

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

这对于我,给出了设备宽度可用于 css 的提示。

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

CSS media queries offer this, as I can say

@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:640px will 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.

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,

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

蓬勃野心 2024-12-03 13:37:28

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

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

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

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.

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

 var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
虐人心 2024-12-03 13:37:28

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 的浏览器。

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.

高冷爸爸 2024-12-03 13:37:28

我只是有这个想法,所以也许它是短视的,但它似乎工作得很好,并且可能是 CSS 和 JS 之间最一致的。

在 CSS 中,您根据 @media screen 值设置 html 的最大宽度值:

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

    html { 
        max-width: 480px;
    }

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

}

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

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

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

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

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


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

  1. 创建一个将存储断点名称的元素,例如 < code>
  2. 使用 css 媒体查询更改此元素的内容属性,例如“大”或“移动”等(与上面相同的基本媒体查询方法,但设置CSS 'content' 属性而不是 'max-width')。
  3. 使用js或jquery获取css内容属性值(jquery例如$('#breakpoint-indicator').css('content');),返回“large”,或“mobile”,等等,具体取决于媒体查询设置的内容属性。
  4. 根据当前值采取行动。

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

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

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.

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

@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:

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.


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:

  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.

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) {}.

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.

尽揽少女心 2024-12-03 13:37:28

你应该使用

document.documentElement.clientWidth

它被视为跨浏览器兼容性,并且与 jQuery(window).width(); 相同的方法;用途。

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

You should use

document.documentElement.clientWidth

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

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

︶葆Ⅱㄣ 2024-12-03 13:37:28

检查一下

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

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

鸢与 2024-12-03 13:37:28

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

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

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

This should handle most scenarios.

青瓷清茶倾城歌 2024-12-03 13:37:28

您可以轻松使用

document.documentElement.clientWidth

Update

例如:

let el = document.getElementById('result');
el.innerText = document.documentElement.clientWidth;
window.addEventListener('resize', function(event) {
    // do what you want
    el.innerText = document.documentElement.clientWidth;
}, true);
<!DOCTYPE html>
  <html>
     <body>
      <div id="result"></div>
     </body>
  </html>

You can easily use

document.documentElement.clientWidth

Update

For example:

let el = document.getElementById('result');
el.innerText = document.documentElement.clientWidth;
window.addEventListener('resize', function(event) {
    // do what you want
    el.innerText = document.documentElement.clientWidth;
}, true);
<!DOCTYPE html>
  <html>
     <body>
      <div id="result"></div>
     </body>
  </html>

不必你懂 2024-12-03 13:37:28

根据 Bootstrap 用于设置其响应式断点的方法,以下内容函数根据屏幕宽度返回 xs、sm、md、lg 或 xl:

console.log(breakpoint());

function breakpoint() {
    let breakpoints = {
        '(min-width: 1200px)': 'xl',
        '(min-width: 992px) and (max-width: 1199.98px)': 'lg',
        '(min-width: 768px) and (max-width: 991.98px)': 'md',
        '(min-width: 576px) and (max-width: 767.98px)': 'sm',
        '(max-width: 575.98px)': 'xs',
    }

    for (let media in breakpoints) {
        if (window.matchMedia(media).matches) {
            return breakpoints[media];
        }
    }

    return null;
}

Based on the method Bootstrap uses to set its Responsive breakpoints, the following function returns xs, sm, md, lg or xl based on the screen width:

console.log(breakpoint());

function breakpoint() {
    let breakpoints = {
        '(min-width: 1200px)': 'xl',
        '(min-width: 992px) and (max-width: 1199.98px)': 'lg',
        '(min-width: 768px) and (max-width: 991.98px)': 'md',
        '(min-width: 576px) and (max-width: 767.98px)': 'sm',
        '(max-width: 575.98px)': 'xs',
    }

    for (let media in breakpoints) {
        if (window.matchMedia(media).matches) {
            return breakpoints[media];
        }
    }

    return null;
}

做个ˇ局外人 2024-12-03 13:37:28

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

或者更疯狂的事情:

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

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

Or something crazier:

for (var i = 100; !window.matchMedia('(max-device-width: ' + i + 'px)').matches; i++) {}
var deviceWidth = i;
陪我终i 2024-12-03 13:37:28

是的,你可以使用 document.documentElement.clientWidth 来获取客户端的设备宽度,并通过 setInterval 来跟踪设备宽度,

就像

setInterval(function(){
        width = document.documentElement.clientWidth;
        console.log(width);
    }, 1000);

Ya mybe u can use document.documentElement.clientWidth to get the device width of client and keep tracking the device width by put on setInterval

just like

setInterval(function(){
        width = document.documentElement.clientWidth;
        console.log(width);
    }, 1000);
○闲身 2024-12-03 13:37:28

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

Just as an FYI, there is a library called breakpoints which 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文