div 하단으로 스크롤 하시겠습니까?
레일에서 ajax 요청을 사용하여 채팅을 만들고 있으며 div가 많은 운없이 맨 아래로 스크롤되도록 노력하고 있습니다.
이 div의 모든 것을 래핑합니다.
#scroll {
height:400px;
overflow:scroll;
}
JS를 사용하여 기본적으로 아래쪽으로 스크롤하는 방법이 있습니까?
ajax 요청 후 아래로 스크롤하는 방법이 있습니까?
내 사이트에서 사용하는 내용은 다음과 같습니다.
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
jQuery scrollTop을 사용하는 경우 훨씬 쉽습니다 .
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
사용 의 jQuery 애니메이션을 :
$('#DebugContainer').stop().animate({
scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);
다음 코드를 사용할 수 있습니다.
function scrollToBottom(id){
var div = document.getElementById(id);
div.scrollTop = div.scrollHeight - div.clientHeight;
}
JQuery 로 부드러운 스크롤 을 수행하려면 :
function scrollSmoothToBottom (id) {
var div = document.getElementById(id);
$('#' + id).animate({
scrollTop: div.scrollHeight - div.clientHeight
}, 500);
}
JSFiddle 의 예 를 참조하십시오.
그리고 그것이 작동하는 방법입니다 :
참조 : scrollTop , scrollHeight , clientHeight
var mydiv = $("#scroll");
mydiv.scrollTop(mydiv.prop("scrollHeight"));
jQuery 1.6에서 작동
https://api.jquery.com/scrollTop/
Newer method that works on all current browsers:
this.scrollIntoView(false);
If you don't want to rely on scrollHeight
, the following code helps:
$('#scroll').scrollTop(1000000);
smooth scroll with Javascript:
document.getElementById('messages').scrollIntoView({ behavior: 'smooth', block: 'end' });
Using jQuery, scrollTop is used to set the vertical position of scollbar for any given element. there is also a nice jquery scrollTo plugin used to scroll with animation and different options (demos)
var myDiv = $("#div_id").get(0);
myDiv.scrollTop = myDiv.scrollHeight;
if you want to use jQuery's animate method to add animation while scrolling down, check the following snippet:
var myDiv = $("#div_id").get(0);
myDiv.animate({
scrollTop: myDiv.scrollHeight
}, 500);
Javascript or jquery:
var scroll = document.getElementById('messages');
scroll.scrollTop = scroll.scrollHeight;
scroll.animate({scrollTop: scroll.scrollHeight});
Css:
.messages
{
height: 100%;
overflow: auto;
}
Found this really helpful, thank you.
For the Angular 1.X folks out there:
angular.module('myApp').controller('myController', ['$scope', '$document',
function($scope, $document) {
var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;
}
]);
Just because the wrapping in jQuery elements versus HTML DOM elements gets a little confusing with angular.
Also for a chat application, I found making this assignment after your chats were loaded to be useful, you also might need to slap on short timeout as well.
small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside ">= comparison"):
var objDiv = document.getElementById(id);
var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);
// add new content to div
$('#' + id ).append("new line at end<br>"); // this is jquery!
// doScroll is true, if we the bottom line is already visible
if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;
Just as a bonus snippet. I'm using angular and was trying to scroll a message thread to the bottom when a user selected different conversations with users. In order to make sure that the scroll works after the new data had been loaded into the div with the ng-repeat for messages, just wrap the scroll snippet in a timeout.
$timeout(function(){
var messageThread = document.getElementById('message-thread-div-id');
messageThread.scrollTop = messageThread.scrollHeight;
},0)
That will make sure that the scroll event is fired after the data has been inserted into the DOM.
You can also, using jQuery, attach an animation to html,body
of the document via:
$("html,body").animate({scrollTop:$("#div-id")[0].offsetTop}, 1000);
which will result in a smooth scroll to the top of the div with id "div-id".
This will let you scroll all the way down regards the document height
$('html, body').animate({scrollTop:$(document).height()}, 1000);
I have encountered the same problem, but with an additional constraint: I had no control over the code that appended new elements to the scroll container. None of the examples I found here allowed me to do just that. Here is the solution I ended up with .
It uses Mutation Observers
(https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) which makes it usable only on modern browsers (though polyfills exist)
So basically the code does just that :
var scrollContainer = document.getElementById("myId");
// Define the Mutation Observer
var observer = new MutationObserver(function(mutations) {
// Compute sum of the heights of added Nodes
var newNodesHeight = mutations.reduce(function(sum, mutation) {
return sum + [].slice.call(mutation.addedNodes)
.map(function (node) { return node.scrollHeight || 0; })
.reduce(function(sum, height) {return sum + height});
}, 0);
// Scroll to bottom if it was already scrolled to bottom
if (scrollContainer.clientHeight + scrollContainer.scrollTop + newNodesHeight + 10 >= scrollContainer.scrollHeight) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
});
// Observe the DOM Element
observer.observe(scrollContainer, {childList: true});
I made a fiddle to demonstrate the concept : https://jsfiddle.net/j17r4bnk/
Java Script:
document.getElementById('messages').scrollIntoView(false);
Scrolls to the last line of the content present.
A very simple method to this is to set the scroll to
to the height of the div.
var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);
Scroll to the last element inside the div:
myDiv.scrollTop = myDiv.lastChild.offsetTop
I know this is an old question, but none of these solutions worked out for me. I ended up using offset().top to get the desired results. Here's what I used to gently scroll the screen down to the last message in my chat application:
$("#html, body").stop().animate({
scrollTop: $("#last-message").offset().top
}, 2000);
I hope this helps someone else.
use :
var element= $('element');
var maxScrollTop = element[0].scrollHeight - element.outerHeight();
element.scrollTop(maxScrollTop);
or check scroll to bottom :
var element = $(element);
var maxScrollTop = element[0].scrollHeight - element.outerHeight();
element.on('scroll', function() {
if ( element.scrollTop() >= maxScrollTop ) {
alert('scroll to bottom');
}
});
If this is being done for scrolling to the bottom of chat window, do the following
The idea of scrolling to a particular div in the chat was the following
1) Person, 시간 및 메시지로 구성된 각 채팅 div는 chatContentbox 클래스와 함께 for 루프에서 실행됩니다.
2) querySelectorAll은 이러한 모든 배열을 찾습니다. 400 개의 노드 (400 개의 채팅)가 될 수 있습니다.
3) 마지막으로 이동
4) scrollIntoView ()
let lastChatBox = document.querySelectorAll('.chatContentBox');
lastChatBox = lastChatBox[lastChatBox.length-1];
lastChatBox.scrollIntoView();
참고 URL : https://stackoverflow.com/questions/270612/scroll-to-bottom-of-div
'Program Tip' 카테고리의 다른 글
신경망에서 편향의 역할 (0) | 2020.09.29 |
---|---|
코드가있는 어셈블리의 경로를 어떻게 얻습니까? (0) | 2020.09.29 |
Git-치명적 : '/path/my_project/.git/index.lock'을 만들 수 없음 : 파일이 있습니다. (0) | 2020.09.29 |
리소스가 이미있는 경우 POST에 대한 HTTP 응답 코드 (0) | 2020.09.29 |
jQuery없이 AJAX 호출을 만드는 방법은 무엇입니까? (0) | 2020.09.29 |