需求
- 当用户没有滚动时,滚动条默认滚动至底部。
- 当用户滚动时,滚动条暂停滚动。直至用户滚动到底部后,重新开始自动置底。
注意事项
scrollHeight
- 包含元素的垂直内边距和边框,水平滚动条的高度,且是一个整数
clientHeight 与 offsetHeight
- clientHeight 仅仅包含内边距 + 高度
- offsetHeight 包含内边距 + 滚动条 + 边框
- clientHeight + 滚动条高度 + 边框 = offsetHeight
demo
var scrollStatus = true
var body = document.body
var intervalId = setInterval(() => {
var h1 = document.createElement('h1')
h1.innerText = 'test'
body.appendChild(h1)
if(scrollStatus) {
body.scrollTop = body.scrollHeight - body.clientHeight
}
},500)
body.addEventListener('scroll', function (e) {
if(body.scrollHeight - body.clientHeight - 5 <= body.scrollTop) {
scrollStatus = true
} else {
scrollStatus = false
}
})