首页 > 解决方案 > 当滚动条不存在时,jquery width() 不正确

问题描述

我正在使用 jQuery 3.3.1,width()即使不存在滚动条,该函数似乎也会从元素的实际宽度中减去滚动条的宽度。根据 chrome 开发工具,该元素的宽度为 1128.37px,但 jquery 返回其宽度为 1111.38px。17px 是滚动条的宽度。

当我增加页面长度以显示滚动条时,此问题得到解决,然后 css 宽度也减小到 1111.38。我已经尝试了其他类似答案中的所有解决方案,但它们都不起作用。

这似乎与github 上的这个问题有关,但看起来没有解决方案。

那么我怎么知道我是否有滚动条呢?如何始终如一地获得元素的宽度?

标签: jquerycss

解决方案


使用.innerWidth()并确保该元素具有box-sizing: border-box. 使用 Chrome 和 Firefox 在 jQuery 3.3.1 上测试。

演示

有两个按钮:第一个按钮切换滚动条,第二个按钮切换box-sizing: border-box样式。

$('.btn1').on('click', function() {
  $(this).toggleClass('h s');
  $('.box').toggleClass('hidden scroll');
  $('.out').val($('.box').innerWidth() + "px");
});

$('.btn2').on('click', function() {
  $(this).toggleClass('on off');
  $('.box').toggleClass('border');
  $('.out').val($('.box').innerWidth() + "px");
});
.box {
  width: 200px;
  height: 200px;
  background: #000
}
.off::after {content: " off"}
.on::after {content: " on"}
.h::before {content: 'no scrollbar';}
.s::before {content: 'scrollbar';}
.hidden {overflow: hidden;}
.scroll {overflow: scroll;}
.border {box-sizing: border-box}
<button class='btn1 h'></button>
<button class='btn2 off'>border-box</button>
<output class='out'></output>
<div class="box hidden"></div>



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读