需求:当div 中 内容过多出现滚动条时,让滚动条滚动到最下面。

scrollTop() 方法返回或设置匹配元素的滚动条的垂直位置。

scrollHeight 网页内容实际高度

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
    <style>
        .out-box {
            width: 300px;
            height: 300px;
            padding: 10px;
            border: 2px solid blue;
            margin: 10px;
            overflow: auto;
        }
        p {
            line-height: 40px;
            border-bottom: 1px dashed rebeccapurple;
        }
        .btn {
            background-color: #009688;
            outline: 0;
            display: inline-block;
            height: 38px;
            line-height: 38px;
            padding: 0 18px;
            border: none;
            color: #fff;
            margin-top: 10px;
            cursor: pointer;
        }
        #btn2 {
            background: #0057b7;
        }
    </style>
</head>
<body>
<div class="out-box">
    <p>第一行</p>
    <p>第二行</p>
    <p>第三行</p>
    <p>第四行</p>
    <p>第五行</p>
    <p>第六行</p>
    <p>第七行</p>
    <p>最后一行</p>
</div>
<button class="btn" id="btn">移动到底部</button>
<button class="btn" id="btn2">查看高度值</button>
</body>
</html>
<script src="jquery.min.js"></script>
<script>
$("#btn").on("click", function () {
    var h4 = $('.out-box').prop("scrollHeight"); //等同 $('.out-box')[0].scrollHeight
    $('.out-box').scrollTop(h4);
});

$("#btn2").on("click", function () {
    var h1 = $('.out-box').height();
    console.log("height() 可视区域高度(不包含padding 和 border)=> h1: " + h1);
    var h11 = document.getElementsByClassName("out-box")[0].clientHeight;
    console.log("clientHeight 可视区域高度(包含padding 不包含border)=> h11: " + h11);

    var h2 = $('.out-box')[0].offsetHeight;
    var h22 = document.getElementsByClassName("out-box")[0].offsetHeight;
    console.log("offsetHeight 可见区域高度(包含padding 和 border)=> h2 " + h2 + ' h22: ' + h22);

    var h3 = $('.out-box').scrollTop();
    var h33 = document.getElementsByClassName("out-box")[0].scrollTop;
    console.log("scrollTop 被卷去的高度 => h3 " + h3 + ' h33: ' + h33);

    var h4 = $('.out-box').prop("scrollHeight"); //等同 $('.out-box')[0].scrollHeight
    var h44 = document.getElementsByClassName("out-box")[0].scrollHeight;
    console.log('scrollHeight 内容实际高度 => h4: ' + h4 + ' h44: ' + h44);
});

</script>

1、点击按钮移动到底部:

 2、点击按钮查看高度值:

 

 

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐