2017-02-13 5 views
0

私はajaxクエリによってリフレッシュされている(サイズが増加している)コンテンツを持つscrollviewを持っています。ユーザーが下に移動する場合にのみ、動的スクロールを下に維持する方法?

ユーザーが下にスクロールしているときに(一般的にはすべての場合と同じように)、テキストを追加してもスクロールを下に移動する必要があります。

私がスクロールこのコードと下にあるときに見つけるためにしようと試み:

var scrollDiv = $('#modalText'); 
var height = scrollDiv[0].scrollHeight; 
if (scrollDiv[0].scrollTop==height){ 
//scroll is in the bottom, must force the scroll to bottom 
}else{ 
//scroll is not in the bottom, must maintain the scroll point 
} 

問題はscrollDiv [0] .scrollTopがscrollDivに等しくないことであるユーザがある場合[0] .scrollHeightなぜか、私は理解できませんが、それは約900ピクセル以下です!

誰にでもこの解決策がありますか?

答えて

0

あなたが直面している900の違いは、ビューポート/クライアントの高さのためです。これを計算に追加すると、それはscrollHeight == scrollTop + clientHeightです。これはMozilla Foundationの文書scrollHeightで確認できます。

1

、あなたの答えは良い方法のようですが、私の場合には動作しませんscrollBottom

var scrollDiv = $('#modalText'); 
 

 
function add() { 
 
    var height = scrollDiv[0].scrollHeight; 
 
    var scroll = scrollDiv[0].scrollTop + scrollDiv[0].offsetHeight; 
 

 
    scrollDiv.append('<p>' + Number(new Date()) + '</p>'); 
 

 
    if (scroll == height) { 
 
    //scroll is in the bottom, must force the scroll to bottom 
 
    scrollDiv.scrollTop(height); 
 
    } else { 
 
    //scroll is not in the bottom, must maintain the scroll point 
 
    } 
 
};
#modalText { 
 
    max-height: 180px; 
 
    overflow: auto; 
 
    width: 200px; 
 
    background-color: #f5f5f5; 
 
    padding: 10px; 
 
    box-sizing: border-box; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button onclick="add()">Add</button> 
 
<div id="modalText"></div>

+0

を取得するためにscrollTopheightを追加する必要があります。高さは52058で、スクロールは52048.5なので、同じではありません。あなたは理由を理解していますか? – NullPointerException

+0

これは、パディングが上下にある場合は 'padding'の可能性があります。' scroll = scrollDiv [0] .scrollTop + scrollDiv [0] .offsetHeight; ' – Jag

関連する問題