如何在 JavaScript 中确定水平滚动条的高度或垂直滚动条的宽度?
从 Alexandre Gomes Blog 我没有尝试过。请让我知道这对你有没有用。
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);
};
使用 jQuery,您可以将 Matthew Vines 的答案缩短为:
function getScrollBarWidth () {
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
return 100 - widthWithScroll;
};
如果你正在寻找一个简单的操作,只需混合普通的 dom js 和 jquery,
var swidth=(window.innerWidth-$(window).width());
返回当前页面滚动条的大小。 (如果它是可见的,否则将返回 0)
$(element).width()
是做什么的?没有jQuery怎么写?
这只是我找到的脚本,它在 webkit 浏览器中工作...... :)
$.scrollbarWidth = function() {
var parent, child, width;
if(width===undefined) {
parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');
child=parent.children();
width=child.innerWidth()-child.height(99).innerWidth();
parent.remove();
}
return width;
};
最小化版本:
$.scrollbarWidth=function(){var a,b,c;if(c===undefined){a=$('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');b=a.children();c=b.innerWidth()-b.height(99).innerWidth();a.remove()}return c};
你必须在文件准备好时调用它......所以
$(function(){ console.log($.scrollbarWidth()); });
于 2012 年 3 月 28 日在最新的 FF、Chrome、IE 和 Safari 的 Windows 7 上测试,并且 100% 正常工作。
来源:http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth
width
将总是 === 未定义第一次函数被调用。在对函数 width
的后续调用已经设置,该检查只是防止计算被不必要地再次运行。
width
中,而是重新计算它每一次。它有效,但效率极低。请帮个忙,改用 Alman 插件中的 correct version。
对我来说,最有用的方法是
(window.innerWidth - document.getElementsByTagName('html')[0].clientWidth)
使用香草 JavaScript。
https://i.stack.imgur.com/cDglu.png
document.documentElement.clientWidth
代替。 documentElement
更清晰、更清晰地表达了获取 <html>
元素的意图。
window.scrollBarWidth = function() {
document.body.style.overflow = 'hidden';
var width = document.body.clientWidth;
document.body.style.overflow = 'scroll';
width -= document.body.clientWidth;
if(!width) width = document.body.offsetWidth - document.body.clientWidth;
document.body.style.overflow = '';
return width;
}
我找到了一个适用于页面内部元素而不是页面本身的简单解决方案:$('#element')[0].offsetHeight - $('#element')[0].clientHeight
这将返回 x 轴滚动条的高度。
// 创建测量节点 var scrollDiv = document.createElement("div"); scrollDiv.className = "滚动条测量"; document.body.appendChild(scrollDiv); // 获取滚动条宽度 var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;控制台信息(滚动条宽度); // Mac: 15 // 删除 DIV document.body.removeChild(scrollDiv); .scrollbar-measure { 宽度:100px;高度:100px;溢出:滚动;位置:绝对;顶部:-9999 像素; }
在我的网站上给了我 17 个,在 Stackoverflow 上给了我 14 个。
您可以使用 jquery + javascript 确定带有 document
的 window
滚动条,如下所示:
var scrollbarWidth = ($(document).width() - window.innerWidth);
console.info("Window Scroll Bar Width=" + scrollbarWidth );
这应该可以解决问题,不是吗?
function getScrollbarWidth() {
return (window.innerWidth - document.documentElement.clientWidth);
}
如果您已经有一个带有滚动条的元素,请使用:
function getScrollbarHeight(el) {
return el.getBoundingClientRect().height - el.scrollHeight;
};
如果不存在 horzintscrollbar,该函数将返回 0
Antiscroll.js
在其代码中的做法是:
function scrollbarSize () {
var div = $(
'<div class="antiscroll-inner" style="width:50px;height:50px;overflow-y:scroll;'
+ 'position:absolute;top:-200px;left:-200px;"><div style="height:100px;width:100%"/>'
+ '</div>'
);
$('body').append(div);
var w1 = $(div).innerWidth();
var w2 = $('div', div).innerWidth();
$(div).remove();
return w1 - w2;
};
代码来自这里:https://github.com/LearnBoost/antiscroll/blob/master/antiscroll.js#L447
detectScrollbarWidthHeight: function() {
var div = document.createElement("div");
div.style.overflow = "scroll";
div.style.visibility = "hidden";
div.style.position = 'absolute';
div.style.width = '100px';
div.style.height = '100px';
document.body.appendChild(div);
return {
width: div.offsetWidth - div.clientWidth,
height: div.offsetHeight - div.clientHeight
};
},
在 Chrome、FF、IE8、IE11 中测试。
创建一个空的 div
并确保它出现在所有页面上(即,将其放入 header
模板中)。
给它这个样式:
#scrollbar-helper {
// Hide it beyond the borders of the browser
position: absolute;
top: -100%;
// Make sure the scrollbar is always visible
overflow: scroll;
}
然后只需使用 Javascript 检查 #scrollbar-helper
的大小:
var scrollbarWidth = document.getElementById('scrollbar-helper').offsetWidth;
var scrollbarHeight = document.getElementById('scrollbar-helper').offsetHeight;
无需计算任何内容,因为此 div
将始终具有 scrollbar
的 width
和 height
。
唯一的缺点是您的模板中会有一个空的 div
。但另一方面,您的 Javascript 文件会更干净,因为这只需要 1 或 2 行代码。
function getScrollBarWidth() {
return window.innerWidth - document.documentElement.clientWidth;
}
大多数浏览器使用 15px 作为滚动条宽度
function getWindowScrollBarHeight() {
let bodyStyle = window.getComputedStyle(document.body);
let fullHeight = document.body.scrollHeight;
let contentsHeight = document.body.getBoundingClientRect().height;
let marginTop = parseInt(bodyStyle.getPropertyValue('margin-top'), 10);
let marginBottom = parseInt(bodyStyle.getPropertyValue('margin-bottom'), 10);
return fullHeight - contentHeight - marginTop - marginBottom;
}
使用 jquery(仅在 Firefox 中测试):
function getScrollBarHeight() {
var jTest = $('<div style="display:none;width:50px;overflow: scroll"><div style="width:100px;"><br /><br /></div></div>');
$('body').append(jTest);
var h = jTest.innerHeight();
jTest.css({
overflow: 'auto',
width: '200px'
});
var h2 = jTest.innerHeight();
return h - h2;
}
function getScrollBarWidth() {
var jTest = $('<div style="display:none;height:50px;overflow: scroll"><div style="height:100px;"></div></div>');
$('body').append(jTest);
var w = jTest.innerWidth();
jTest.css({
overflow: 'auto',
height: '200px'
});
var w2 = jTest.innerWidth();
return w - w2;
}
但我实际上更喜欢@Steve 的回答。
这是一个很好的答案:https://stackoverflow.com/a/986977/5914609
但是在我的情况下它不起作用。我花了几个小时寻找解决方案。最后我回到了上面的代码并添加了 !important 到每种样式。它奏效了。我无法在原始答案下方添加评论。所以这里是修复:
function getScrollBarWidth () {
var inner = document.createElement('p');
inner.style.width = "100% !important";
inner.style.height = "200px !important";
var outer = document.createElement('div');
outer.style.position = "absolute !important";
outer.style.top = "0px !important";
outer.style.left = "0px !important";
outer.style.visibility = "hidden !important";
outer.style.width = "200px !important";
outer.style.height = "150px !important";
outer.style.overflow = "hidden !important";
outer.appendChild (inner);
document.body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll !important';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild (outer);
return (w1 - w2);
};
这个生命黑客决定将使您有机会找到浏览器滚动宽度(vanilla JavaScript)。使用此示例,您可以在任何元素上获得 scrollY 宽度,包括根据您当前的设计概念不应该滚动的那些元素,:
getComputedScrollYWidth (el) {
let displayCSSValue ; // CSS value
let overflowYCSSValue; // CSS value
// SAVE current original STYLES values
{
displayCSSValue = el.style.display;
overflowYCSSValue = el.style.overflowY;
}
// SET TEMPORALLY styles values
{
el.style.display = 'block';
el.style.overflowY = 'scroll';
}
// SAVE SCROLL WIDTH of the current browser.
const scrollWidth = el.offsetWidth - el.clientWidth;
// REPLACE temporally STYLES values by original
{
el.style.display = displayCSSValue;
el.style.overflowY = overflowYCSSValue;
}
return scrollWidth;
}
这是基于偏移宽度差异的更简洁易读的解决方案:
function getScrollbarWidth(): number {
// 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;
}
请参阅 JSFiddle。
已经在我的库中编码,所以这里是:
var vScrollWidth = window.screen.width - window.document.documentElement.clientWidth;
我应该提到 jQuery $(window).width()
也可以用来代替 window.document.documentElement.clientWidth
。
如果您在右侧的 Firefox 中打开开发人员工具,它不起作用,但如果在底部打开开发人员窗口,它会克服它!
支持 window.screen
quirksmode.org!
玩得开心!
它似乎有效,但也许有一个更简单的解决方案适用于所有浏览器?
// 创建测量节点 var scrollDiv = document.createElement("div"); scrollDiv.className = "滚动条测量"; document.body.appendChild(scrollDiv); // 获取滚动条宽度 var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;控制台信息(滚动条宽度); // Mac: 15 // 删除 DIV document.body.removeChild(scrollDiv); .scrollbar-measure { 宽度:100px;高度:100px;溢出:滚动;位置:绝对;顶部:-9999 像素; }
我制作了@Matthew Vines 答案的更新版本。
它更容易阅读,更容易理解。它不需要内部元素。为获取滚动条宽度而创建的元素具有 100% 的高度/宽度,因此它不会在低端 PC/手机的主体上创建任何可见的滚动条,这可能需要更多时间来创建元素,获取宽度,最后移除元素。
const getScrollBarWidth = () => {
const e = document.createElement('div');
Object.assign(e.style, {
width: '100%',
height: '100%',
overflow: 'scroll',
position: 'absolute',
visibility: 'hidden',
top: '0',
left: '0',
});
document.body.appendChild(e);
const scrollbarWidth = e.offsetWidth - e.clientWidth;
document.body.removeChild(e);
return scrollbarWidth;
};
console.log(getScrollBarWidth());
我建议只检查一次滚动条宽度,在页面加载时(除非它不符合您的需要),然后将结果存储在状态/变量中。
我在 material-ui
代码中找到了该解决方案,它对我有用。
const scrollbarWidth = window.innerWidth - document.querySelector('body').clientWidth;
您可以使用此解决方案来查找网页内任何元素的滚动条宽度,而不是网页本身。您还可以通过将其与宽度相关的属性替换为与高度相关的对应属性来重写它以在水平滚动条的情况下为滚动条高度工作。
offsetWidth
属性返回内容、内边距、边框和滚动条(如果有)的总宽度。而 clientWidth
属性仅返回内容和填充的总宽度。
因此,如果我们从 offsetWidth
中减去 clientWidth
和水平边框,我们将剩下滚动条的宽度。也就是说,如果有滚动条,我们就会得到滚动条的宽度。但如果没有任何滚动条,我们将得到 0
。
const element = document.querySelector("div");
const elementStyle = window.getComputedStyle(element);
const horizontalBorder = parseFloat(elementStyle.borderLeftWidth) + parseFloat(elementStyle.borderRightWidth);
const scrollbarWidth = element.offsetWidth - element.clientWidth - horizontalBorder + "px";