简体   繁体   English

window.innerwidth的意外行为

[英]Unexpected behaviour of window.innerwidth

if(window.innerWidth) {
    return window.innerWidth;
}
return $(window).width();

I am using the above code to find the available width of a web page. 我使用上面的代码来查找网页的可用宽度。 It works most of the time. 它大部分时间都有效。 But in some mobile browsers (Mobile Chrome and a few) and sometimes in desktop website it returns 0. I don't know, what went wrong? 但在一些移动浏览器(移动Chrome和一些),有时在桌面网站,它返回0.我不知道,出了什么问题?

Mozilla/5.0 (Linux; Android 5.1.1; SM-J500M Build/LMY48B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36 Mozilla / 5.0(Linux; Android 5.1.1; SM-J500M Build / LMY48B)AppleWebKit / 537.36(KHTML,与Gecko一样)Chrome / 56.0.2924.87 Mobile Safari / 537.36

This is one of the user agent where it is failed. 这是失败的用户代理之一。 Mostly it happen in mobile chrome in android browser. 大多数情况下它发生在android浏览器的移动Chrome中。

You might try forcing the test in the if to be a Boolean. 您可以尝试在if强制测试为布尔值。

if(!!window.innerWidth) {
  return window.innerWidth;
}
return $(window).width();

Having more than on return statement in a function is not always considered best practice. 在函数中具有多于return语句并不总是被认为是最佳实践。 You can make this clearer as follows. 你可以更清楚地说明如下。

return !!window.innerWidth ?
   window.innerWidth :
   $(window).width();

If this doesn't work then the issue is that you have found a bug in jQuery's width method. 如果这不起作用,那么问题是您在jQuery的width方法中发现了一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM