javascript滚动条_使用JavaScript检测滚动条宽度

javascript滚动条

I've recently been working on an advanced JavaScript-based grid solution and let me tell you: it's quite an undertaking. Making sure the grid is accessible, reactive, efficient, and cross-browser compatible is difficult, but even the minor workings of each of those are hard. One small task was detecting the width of the vertical scrollbar so that I know how wide the grid body truly was. Here's the tiny snippet to do it:

我最近一直在研究基于JavaScript的高级网格解决方案,并告诉我:这是一项艰巨的任务。 确保网格的可访问性,React性,高效性和跨浏览器兼容性是困难的,但是即使每个网格的细微工作都很难。 一个小任务是检测垂直滚动条的宽度,以便我知道网格体的真正宽度。 这是执行此操作的小片段:

CSS (The CSS)

The element we create for measurement will need to be positioned off screen so the user doesn't notice it:

我们为测量而创建的元素将需要放置在屏幕之外,以便用户不会注意到它:


/* way the hell off screen */
.scrollbar-measure {
	width: 100px;
	height: 100px;
	overflow: scroll;
	position: absolute;
	top: -9999px;
}


You could add these styles directly to the element, but they'd bloat the JavaScript portion a bit.

您可以将这些样式直接添加到元素中,但是它们会使JavaScript部分有些膨胀。

JavaScript (The JavaScript)

The obvious parts is creating a DIV to inject into the DOM and adding the CSS class we created above:

显而易见的部分是创建一个DIV以注入DOM并添加我们在上面创建CSS类:


// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);

// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.warn(scrollbarWidth); // Mac:  15

// Delete the DIV 
document.body.removeChild(scrollDiv);


With the element in the page, subtracting the clientWidth from the offsetWidth gives the scrollbar size! The last step is removing the DIV from the DOM and done!

对于页面中的元素,从clientWidth减去clientWidth offsetWidth得到滚动条的大小! 最后一步是从DOM中删除DIV ,然后完成!

Since the scrollbar size is different between Mac and Windows (and even Internet Explorer 7 vs. other IE versions), this small but dynamic snippet is just what I needed to find the true content area of the container. Feel free to convert this JavaScript snippet into whatever JavaScript framework your prefer!

由于Mac和Windows(甚至Internet Explorer 7与其他IE版本)之间的滚动条大小不同,因此,这个小而动态的代码段正是我找到容器真正内容区域所需要的。 随意将此JavaScript代码段转换为您喜欢的任何JavaScript框架!

翻译自: https://davidwalsh.name/detect-scrollbar-width

javascript滚动条

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值