jQuery窗口宽度不等于CSS的窗口宽度

Ata*_*adj 7 html javascript css jquery

我正在使用以下两段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
}
Run Code Online (Sandbox Code Playgroud)

它们的问题是后者在width = 738px而不是720px上执行.我怀疑这是因为浏览器的垂直滚动条在Chrome中的宽度等于18px.

有没有办法统一这个?我希望这些操作在所有浏览器中同时发生,而不管滚动条的宽度如何.

测试(当浏览器是@ 720px并且CSS已经执行时):

jQuery(document).innerWidth() = 703
jQuery(window).innerWidth() = 703
jQuery(document).width() = 703
jQuery(window).width() = 703
jQuery('body').width() = 703
jQuery('html').width() = 703
Run Code Online (Sandbox Code Playgroud)

Fré*_*idi 7

我不得不在不久前解决同样的问题,到目前为止,我找到的最正确的解决方案是使用媒体查询将实际窗口大小传递给Javascript.您必须遵循以下步骤:

  • 在页面中添加隐藏元素,
  • 使用媒体查询来更改该max-width元素的属性,
  • max-width通过Javascript 读回该元素的属性.

例如,将以下元素添加到页面:

<div id="currentMedia"></div>
Run Code Online (Sandbox Code Playgroud)

然后编写以下CSS规则:

#currentMedia {
    display: none;
}

@media (max-width: 720px) {
    /* Make arrows in the carousel disappear... */

    #currentMedia {
        max-width: 720px;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,从Javascript方面,您可以写:

if (parseInt(jQuery("#currentMedia").css("max-width"), 10) <= 720) {
    // Make arrows in the carousel stop working...
}
Run Code Online (Sandbox Code Playgroud)

无论滚动条大小如何,它都将是准确的,因为该值来自触发旋转木马消失的相同媒体查询.

我在最近的所有主要浏览器上测试了这个解决方案,它给出了正确的结果


Tus*_*har 6

您将在quirksmode.org上找到此页面上哪些浏览器支持哪些属性的大摘要.

你最好的选择可能是在页面中获取一个元素(使用document.body支持,或者document.getElementById或其他),遍历其offsetParent链以找到最顶层的元素,然后检查该元素的clientWidth和clientHeight.

innerWidth文档

innerWidth()说这种方法并不适用于windowdocument对象; 对于这些,请使用.width()

尝试

如何获得浏览器的滚动条大小?

来自Alexandre Gomes博客

function getScrollBarWidth () {
  var inner = document.createElement('p');
  inner.style.width = "100%";
  inner.style.height = "200px";

  var outer = document.createElement('div');
  outer.style.position = "absolute";
  outer.style.top = "0px";
  outer.style.left = "0px";
  outer.style.visibility = "hidden";
  outer.style.width = "200px";
  outer.style.height = "150px";
  outer.style.overflow = "hidden";
  outer.appendChild (inner);

  document.body.appendChild (outer);
  var w1 = inner.offsetWidth;
  outer.style.overflow = 'scroll';
  var w2 = inner.offsetWidth;
  if (w1 == w2) w2 = outer.clientWidth;

  document.body.removeChild (outer);

  return (w1 - w2);
};
Run Code Online (Sandbox Code Playgroud)

在你的代码中

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