Javascript jQuery窗口宽度不等于CSS';窗口宽度

Javascript jQuery窗口宽度不等于CSS';窗口宽度,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我使用以下两段CSS和JS代码: @media (max-width: 720px) { // a code to make arrows in a carousel disappear } if(jQuery(window).width() <= 720){ // a code to make arrows in the carousel stop working } 您将发现哪些浏览器支持哪些属性的大摘要 最好的方法可能是抓取页面中的一个元素(在支持的地方使用doc

我使用以下两段CSS和JS代码:

@media (max-width: 720px) {
    // a code to make arrows in a carousel disappear
}

if(jQuery(window).width() <= 720){
    // a code to make arrows in the carousel stop working
}

您将发现哪些浏览器支持哪些属性的大摘要

最好的方法可能是抓取页面中的一个元素(在支持的地方使用document.body,或者document.getElementById或其他什么),遍历其offsetParent链以找到最顶端的元素,然后检查该元素的clientWidth和clientHeight

文件

innerWidth()
表示此方法不适用于
窗口
文档
对象;对于这些,请使用.width()

试一试

在代码中

if(jQuery(window).width()-getScrollBarWidth(); <= 720){
    // a code to make arrows in the carousel stop working
}

if(jQuery(window).width()-getScrollBarWidth();我不久前也遇到过同样的问题,到目前为止,我找到的最正确的解决方案是使用媒体查询将实际的窗口大小传递给Javascript。您必须遵循以下步骤:

  • 在页面中添加隐藏元素
  • 使用媒体查询更改该元素的
    max width
    属性
  • 通过Javascript读回该元素的
    max width
    属性
例如,将以下元素添加到页面:


然后编写以下CSS规则:

#当前媒体{
显示:无;
}
@介质(最大宽度:720px){
/*使旋转木马中的箭头消失*/
#当前媒体{
最大宽度:720px;
}
}
然后,从Javascript方面,您可以编写:


if(parseInt(jQuery(#currentMedia”).css(“max width”),10)如果您使用的是Bootstrap>3,那么我会给您一些建议

Bootstrap附带了Css和预定义的
.container
类,并使用@media查询对其进行更改。下面是我的工作代码示例

function detectWidth(){
   var width = $('.container').eq(0).outerWidth()   ;
   console.log(width);
   if(width<750){
     // do something for XS element
   }else if(width>=750 && width<970){
     // do something for SM element
   }else if(width>=970 && width<1170){
      // do something for MD element
   }else{
    // do something for LG element
   }
function detectedwidth(){
var width=$('.container').eq(0).outerWidth();
控制台。原木(宽度);

如果(width=750&&width=970&&width我意识到这是一条老线索,但我认为它仍然可以从这个答案中受益

var width = window.outerWidth;

这将为您提供包括滚动条在内的窗口宽度,我相信这是媒体查询所使用的。

有点过时,但我找到了这个解决方案

function getWidth(){
   return ((window.innerWidth > 0) ? window.innerWidth : screen.width);
}

for
innerWidth()
表示此方法不适用于
window
document
对象;对于这些对象,请使用
.width()
。我尝试了此方法,但我认为它不起作用。我使用
console.log()
打印值,结果如下:(当viewport为734px时,它认为它是717px。JavaScript的执行比CSS媒体查询早。这些17px的差异听起来像是浏览器滚动条的宽度。@Atadj很乐意帮助您:)这很聪明,谢谢!所以,没有简单的jQuery方法可以做到这一点?@Atadj,据我所知,没有。
var width = window.outerWidth;
function getWidth(){
   return ((window.innerWidth > 0) ? window.innerWidth : screen.width);
}