use*_*531 105 javascript
以下HTML将在div.container的右侧内侧边缘显示滚动条.
是否可以确定滚动条的宽度?
<div class="container" style="overflow-y:auto; height:40px;">
<div class="somethingBig"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
los*_*rce 216
这个函数应该给你滚动条的宽度
function getScrollbarWidth() {
// Creating invisible container
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.overflow = 'scroll'; // forcing scrollbar to appear
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
document.body.appendChild(outer);
// Creating inner element and placing it in the container
const inner = document.createElement('div');
outer.appendChild(inner);
// Calculating difference between container's full width and the child width
const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);
// Removing temporary elements from the DOM
outer.parentNode.removeChild(outer);
return scrollbarWidth;
}
Run Code Online (Sandbox Code Playgroud)
这里的基本步骤是:
这里的工作示例:http://jsfiddle.net/UU9kg/17/
更新
如果您在Windows(metro)应用程序上使用它,请确保将"外部"div 的-ms-overflow-style属性设置为scrollbar
,否则将无法正确检测宽度.(代码更新)
更新#2 这在Mac OS上无效,默认情况下"滚动时只显示滚动条"设置(Yosemite和up).
Vas*_*nyk 25
// offsetWidth包括滚动条的宽度,而clientWidth则不包含.按规则,它等于14-18px.所以:
var scrollBarWidth = element.offsetWidth - element.clientWidth;
Run Code Online (Sandbox Code Playgroud)
pim*_*vdb 12
如果孩子占用容器的整个宽度(不包括滚动条)(默认值),则可以减去宽度:
var child = document.querySelector(".somethingBig");
var scrollbarWidth = child.parentNode.offsetWidth - child.offsetWidth;
Run Code Online (Sandbox Code Playgroud)
Ujj*_*pta 11
我认为这将简单快速 -
var scrollWidth= window.innerWidth-$(document).width()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
100271 次 |
最近记录: |