scroll 家族
使用场景:
我们想要页面滚动一段距离,比如100px,就让某些元素显示或隐藏
怎么知道页面滚动了100px,就可以使用scroll来检测页面滚动的距离
获取宽高:
获取元素的内容总宽高(包含滚动条)返回值不带单位
scrollWidth
和scrollHeight
div.addEventListener('scroll', function () {
console.log(this.scrollWidth) // 内容的宽
console.log(this.scrollHeight) // 内容的高
})
获取位置:
获取元素内容往左、往上滚出去看不到的距离
scrollLeft
和scrollTop
这两个属性是可以修改的
div.addEventListener('scroll', function () {
console.log(this.scrollLeft) //
console.log(this.scrollTop) //
})
开发中经常检测页面滚动的距离,比如页面滚动100像素,就可以显示一个元素,或者固定一个元素
// 页面滚动事件
window.addEventListener('scroll', function () {
// document.documentElement.scrollTop 获得当前页面被卷去的头部
let num = document.documentElement.scrollTop
console.log(num)
})
offset 家族
使用场景:
上面滚动多少距离,都是我们自己算的,最好是页面滚动到某个元素,就可以做某些事
简单来说,就是通过JS的方式,得到元素在页面中的位置这样我们可以做,页面滚动到这个位置,就显示返回顶部的小盒子
获取宽高:
获取元素的自身宽高、包含元素自身的宽高、padding、boeder
offsetWidth
和offsetHeight
console.log(div.offsetWidth)
console.log(div.offsetHeight)
获取位置:
获取元素距离自己定位父级元素的左、上距离,如果没有则以文档左上角为准
offsetLeft
和offsetTop
这两个属性是只读属性
console.log(div.offsetLeft)
console.log(div.offsetTop)
头部滑动指定位置固定案例
// 1. 页面滚动事件
window.addEventListener('scroll', function () {
// 要检测滚动的距离
// console.log(document.documentElement.scrollTop)
// console.log(sk.offsetTop)
// 2. 要检测滚动的距离 >= 秒杀模块的offsetTop 则滑入
if (document.documentElement.scrollTop >= div.offsetTop) {
header.style.top = '0'
} else {
header.style.top = '-80px'
}
})
电梯导航案例
// 点击谁,谁高亮
for (let i = 0; i < items.length; i++) {
items[i].addEventListener('click', function () {
// 排它
/* for (let j = 0; j < items.length; j++) {
items[j].classList.remove('active')
} */
// 找到上一个active 移除类
document.querySelector('.aside .active').classList.remove('active')
// 点击谁谁添加类
this.classList.add('active')
// 右侧内容跟随走动 让页面滚动到对应的offsetTop值位置
// console.log(neirongs[i].offsetTop) 不用给单位
document.documentElement.scrollTop = neirongs[i].offsetTop
})
}
client 家族
获取宽高:
获取元素的可见部分宽高(不包含边框、滚动条等)
clientWidth
和clientHeight
console.log(div.clientWidth)
console.log(div.clientHeight)
获取位置:
获取元左边框和上边框宽度
clientLeft
和clientTop
这两个属性是只读属性
console.log(div.clientLeft)
console.log(div.clientTop)
窗口尺寸改变触发事件
window.addEventListener('rssize', funtion () {
// 执行的代码
})
检测屏幕宽度
window.addEventListener('rssize', funtion () {
let user_width = document.documentElement.clientWidth
console.log(user_width)
})