2016-12-31 273 views
1

我試圖在點擊滾動到div的底部時得到一個自動滾動。我有它的工作,但它一次只能滾動600px,因爲這是我的設置。我只是不知道如何讓它直接滾動到一次點擊底部的股利。這是我迄今爲止。我不知道是否有更簡單的方式來編寫我所做過的jQuery代碼。滾動到div的底部

$('.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>

回答

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>