***获取 滚动条高度***
// 获取 滚动条高度
console.log(window.pageYOffset); //这里window.scrollY也可,但兼容性差
console.log(document.documentElement.scrollTop); // chrome下document.body.scrollTop值恒为0
console.log($(window).scrollTop());
console.log($("html,body").scrollTop());
console.log($(document).scrollTop());
更改:很多技术博客有误!!!详见浏览器 窗口 scrollTop 的兼容性问题,这个比较好。
总结:只要记住一条
if(window.pageYOffset){//这一条滤去了大部分, 只留了IE678
}else if(document.documentElement.scrollTop ){//IE678 的非quirk模式
}else if(document.body.scrolltop){//IE678 的quirk模式
}
原则是看pageYOffset 然后看documentElement.scrollTop, 最后是document.body.scrollTop
当然 也可以直接scrollTop 而不使用pageYOffset:
document.documentElement.scrollTop || document.body.scrollTop
以下是MDN 提供的兼容性代码:
scrolltop = (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.scrollTop == ‘number’ ? t : document.body).scrollTop
***获取滚动条 本身的 宽度***
//获取 滚动条自身 的宽度,注释掉的不是重点!!
function getScrollbarWidth() {
// 创建外层div,让它始终显示滚动条
const outer = document.createElement('div');
//outer.style.visibility = 'hidden';
// 强制显示滚动条
outer.style.overflow = 'scroll';
// needed for WinJS apps
//outer.style.msOverflowStyle = 'scrollbar';
document.body.appendChild(outer);
// 创建内层div
const inner = document.createElement('div');
outer.appendChild(inner);
// 外层div减去内层div,得到的就是滚动条的宽度(横向就是高度)
const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);
// 移除div
outer.parentNode.removeChild(outer);
return scrollbarWidth;
}
注意(与讨论中心无关):
1、如果在Windows(metro)应用程序上使用此功能,请确保将“外部” div 的-ms-overflow-style属性设置为scrollbar,否则将无法正确检测到宽度。(代码已更新)
2、在默认设置为“仅在滚动时显示滚动条”(Yosemite及更高版本)的Mac OS上,这将不起作用。
***浏览器 宽度***
// 浏览器窗口可视区 宽度 / 浏览器一屏的宽度,(不包含滚动条)
console.log(document.body.clientWidth); // 或document.documentElement
console.log($(document.body).width()); // $(document.documentElement), $("html,body") 和 $(window)都可
console.log(window.innerWidth); // 包含 window窗口 的滚动条宽度!
console.log($(document).width()); // 取当前document的实际width,和 浏览器窗口可视区width(不包含滚动条) 两者中的 最大值!
console.log(window.outerWidth); // Chrome测试发现:总是比innerWidth 多14px~16px;当浏览器窗口最大化时,两者值相等。
***浏览器 高度***
// (貌似)比 整个浏览器窗口高度 小14px~16px !
console.log(window.outerHeight);
// 浏览器可视区 高度 / 浏览器一屏的高度,(不包含滚动条)
console.log(document.documentElement.clientHeight);
console.log($(window).height());
console.log(window.innerHeight); // 包含window窗口的滚动条宽度!
// 获取当前document 的实际内容height
console.log(document.body.clientHeight);//这个比较奇怪,但事实如此!
console.log(document.body.scrollHeight);
console.log(document.documentElement.scrollHeight);
console.log($(document.body).height()); // $(document.documentElement)和 $("html,body")
问:如何获取当前页面卷上去高度?
答://详见 页头内容,二者需要考虑不同浏览器的 兼容性【scrollTop属性可读写,可js控制滚动条的位置】
document.body.scrollTop || document.documentElement.scrollTop
问:一张网页卷上去最大高度(内容实际高度 - 浏览器一屏的高度)是多少?
document.body.clientHeight 、document.body.scrollHeight 、或者document.documentElement.scrollHeight。再 减去document.documentElement.clientHeight