滚动到div的底部

时间:2016-12-31 22:56:20

标签: jquery css

我想点击一下自动滚动滚动到div的底部。我有它的工作,但它只能一次向下滚动600px,就像我设置的那样。我只是不确定如何让它一次点击直接滚动到div的底部。这就是我到目前为止所拥有的。我不知道是否有一种更简单的方法来编写我迄今为止所做的jquery代码。

 $('.scroll-down').on('click', function() {
   var currentScrollPosition = 0;
   currentScrollPosition += 600;
   $('.bx-viewport').animate({
     scrollTop: currentScrollPosition
   }, 2000);
 });
 $('.scroll-up').on('click', function() {
   var currentScrollPosition = 0;
   currentScrollPosition -= 600;
   $('.bx-viewport').animate({
     scrollTop: currentScrollPosition
   }, 2000);
 });
.bx-viewport {
  height: 600px !important;
  overflow: auto !important;
  width: 100%;
  position: relative
}
.scroll-up {
  position: absolute;
  top: 20px;
  right: 100px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.5);
}
.scroll-down {
  position: absolute;
  top: 40px;
  right: 100px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.5);
}
img {
  height: 900px;
  overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bx-viewport">
  <img src="http://placehold.it/200x1000" />
</div>
<div class="scroll-down">scroll down</div>
<div class="scroll-up">scroll up</div>

1 个答案:

答案 0 :(得分:0)

使用scrollHeight属性并减去元素的高度以找到要滚动的可用空间。

$('.scroll-down').on('click', function() {
   var target = $('.bx-viewport'),
       height = target.height(),
       scrollHeight = target.prop('scrollHeight');
  
   target.animate({
     scrollTop: scrollHeight-height
   }, 2000);
 });

 $('.scroll-up').on('click', function() {
   $('.bx-viewport').animate({
     scrollTop: 0
   }, 2000);
 });
.bx-viewport {
  height: 600px !important;
  overflow: auto !important;
  width: 100%;
  position: relative
}
.scroll-up {
  position: absolute;
  top: 20px;
  right: 100px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.5);
}
.scroll-down {
  position: absolute;
  top: 40px;
  right: 100px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.5);
}
img {
  height: 900px;
  overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bx-viewport">
  <img src="http://placehold.it/200x1000" />
</div>
<div class="scroll-down">scroll down</div>
<div class="scroll-up">scroll up</div>