现在有很多插件帮我们封装了很多利用滚动相关实现的功能,但是有时候我们的需求比较特殊的时候,插件无法实现,这时候我们就需要对滚动相关的js知识进行掌握了才能进行开发。今天就给大家介绍几个常用的滚动相关的方法:
一、获取滚动条距离
function getScrollOffset() {
if (window.pageXOffset) {
return {
scrollLeft: window.pageXOffset,
scrollTop: window.pageYOffset
}
} else {
return {
scrollLeft: document.documentElement.scrollLeft + document.body.scrollLeft,
scrollTop: document.documentElement.scrollTop + document.body.scrollTop
}
}
}
二、获取可视区域的宽高
function getViewSize () {
if (window.innerWidth) {
return {
width: window.innerWidth,
height: window.innerHeight
}
} else {
if (document.compatMode === 'BackCompat') {
return {
width: document.body.clientWidth,
height: document.body.clientHeight
}
} else {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
}
}
}
}
三、获取文档的宽高
function getScrollSize () {
if (document.body) {
return {
width: document.body.scrollWidth,
height: document.body.scrollHeight
}
} else {
return {
width: document.documentElement.scrollWidth,
height: document.documentElement.scrollHeight
}
}
}
四、获取指定元素到浏览器左边和顶部的距离
function getElPosition (el) {
var parent = el.offsetParent,
offsetLeft = el.offsetLeft,
offsetTop = el.offsetTop
while(parent) {
offsetLeft += parent.offsetLeft
offsetTop += parent.offsetTop
parent = parent.offsetParent
}
return {
offsetLeft: offsetLeft,
offsetTop: offsetTop
}
}
今天的分享就到这里了,感谢您的收看,一起学习一起进步