jquery - 当滚动条不存在时,jquery width() 不正确
问题描述
我正在使用 jQuery 3.3.1,width()
即使不存在滚动条,该函数似乎也会从元素的实际宽度中减去滚动条的宽度。根据 chrome 开发工具,该元素的宽度为 1128.37px,但 jquery 返回其宽度为 1111.38px。17px 是滚动条的宽度。
当我增加页面长度以显示滚动条时,此问题得到解决,然后 css 宽度也减小到 1111.38。我已经尝试了其他类似答案中的所有解决方案,但它们都不起作用。
这似乎与github 上的这个问题有关,但看起来没有解决方案。
那么我怎么知道我是否有滚动条呢?如何始终如一地获得元素的宽度?
解决方案
使用.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>
推荐阅读
- .net-core - MMALSharp 单摄像头双预览带叠加
- python - 如何在 PyTest 中使用一个夹具的数据集作为另一个夹具的参数?
- java - 如何重置系统属性 javax.net.ssl.trustStorePassword?
- xml - Progress PRODATASET - 在 10.1C 中是否有等效的父 ID 字段?还是替代方案?
- python - 我无法使用 python 正确调整谷歌电子表格正文
- python - 如何在 ECDF 图上使用标记
- windows - 将 .ps1 转换为 .bat 不会导致 cmd.exe 达到最大字符长度 - 但为什么呢?
- javascript - 如何在更改输入字段上更改图表 JS 标题文本?
- questdb - QuestDB:如何配置内存使用?
- javascript - 数据表的搜索框长度重叠