js让滚动条滚动到容器的指定高度

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ddddd</title>
</head>
<body>
    <script src="jquery.js"></script>
    <div id="thisMainPanel" style="height:200px;overflow-y: scroll;border:1px solid #f3f3f3;">
        <div class="son-panel">类容区域-1</div>
        <div class="son-panel">类容区域-2</div>
        <div class="son-panel">类容区域-3</div>
        <div class="son-panel">类容区域-4</div>
        <div class="son-panel" style="height:160px;">我是类容区域-5</div>
        <div class="son-panel">类容区域-6</div>
        <div class="son-panel">类容区域-7</div>
        <div class="son-panel">类容区域-8</div>
    </div>
    <script>
        onload = function () {
          //初始化
          scrollToLocation('#thisMainPanel','.son-panel:last');
        };
        function scrollToLocation(boxCont,scrollTo) {
          var boxContainer = $(boxCont),
          scrollToContainer = boxContainer.find(scrollTo);//滚动到<div id="thisMainPanel">中类名为son-panel的最后一个div处
          //scrollToContainer = boxContainer.find('.son-panel:eq(5)');//滚动到<div id="thisMainPanel">中类名为son-panel的第六个处
          //非动画效果
          console.log(scrollToContainer.offset().top - boxContainer.offset().top + boxContainer.scrollTop())
          boxContainer.scrollTop(
           // scrollToContainer.offset().top - boxContainer.offset().top + boxContainer.scrollTop()
           293
          );
          //动画效果
          // boxContainer.animate({
          //   scrollTop: scrollToContainer.offset().top - boxContainer.offset().top + boxContainer.scrollTop()
          // }, 2000);//2秒滑动到指定位置
        }
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/adolfvicto/p/8968464.html