本文章相关的属性:scrollHeight,clientHeight,scrollTop,offsetHeight
(1)控制元素滚动条滚动到顶部: element.scrollTop = 0;
(2)控制元素滚动条滚动到底部: element.scrollTop = element.scrollHeight - element.clientHeight; 或者直接 element.scrollTop = element.scrollHeight; 【利用了其特性:如果设置了超出这个容器可滚动的值, scrollTop
会被设为最大值。】
示例1:实现滚动条缓慢滚动到底部
元素可滚动距离计算公式: let canScrollDistance = element.scrollHeight - element.clientHeight;
<style>
* {
margin: 0;
}
#father {
box-sizing: border-box;
width: 150px;
height: 150px;
padding: 20px;
border: 10px solid green;
background: red;
overflow: auto;
}
#son {
width: 50px;
height: 250px;
background: blue;
line-height: 250px;
text-align: center;
}
</style>
<body>
<div id="father">
<div id="son">son</div>
</div>
</body>
<script>
var father = document.getElementById("father");
// 没有垂直滚动条时,scrollHeight和clientHeight相等
console.log(father.scrollHeight) //
console.log(father.clientHeight) //
console.log(father.scrollTop) //
console.log(father.offsetHeight) //
let totalScrollDistance = father.scrollHeight - father.clientHeight; // 可滚动距离
let perScrollDistance = Math.ceil(totalScrollDistance/4); // 每次滚动的距离
console.log("可滚动的距离:" + totalScrollDistance)
console.log("每次滚动的距离:" + perScrollDistance)
let timer = setInterval(function(){
if (father.scrollTop < totalScrollDistance) {
father.scrollTop = father.scrollTop + perScrollDistance;
console.log(father.scrollTop)
} else {
clearInterval(timer);
}
}, 2000)
</script>
示例2:
<style>
* {
margin: 0;
box-sizing: border-box;
}
#father {
width: 150px;
height: 150px;
padding-left: 10px;
background: #fff;
overflow: auto;
}
.son {
padding-bottom: 5px;
}
.son-content {
height: 50px;
border: 5px solid green;
padding: 5px;
background: blue;
line-height: 30px;
text-align: center;
font-size: 12px;
color: #fff;
}
</style>
<body>
<div id="father">
<div class="son">
<div class="son-content">
son0
</div>
</div>
<div class="son">
<div class="son-content">
son2
</div>
</div>
<div class="son">
<div class="son-content">
son3
</div>
</div>
<div class="son">
<div class="son-content">
son4
</div>
</div>
<div class="son">
<div class="son-content">
son5
</div>
</div>
</div>
</body>
<script>
let father = document.getElementById("father");
// 没有垂直滚动条时,scrollHeight和clientHeight相等
console.log(father.scrollHeight) //
console.log(father.clientHeight) //
console.log(father.scrollTop) //
console.log(father.offsetHeight) //
let son = document.getElementsByClassName('son')[0];
if (son) {
sonHeight = son.offsetHeight;
let totalScrollDistance = father.scrollHeight - father.clientHeight; // 可滚动距离
let perScrollDistance = sonHeight; // 每次滚动的距离
console.log("可滚动的距离:" + totalScrollDistance)
console.log("每次滚动的距离:" + perScrollDistance)
let timer = setInterval(function(){
if (father.scrollTop < totalScrollDistance) {
father.scrollTop = father.scrollTop + perScrollDistance;
console.log(father.scrollTop)
} else {
clearInterval(timer);
}
}, 2000)
}
</script>