사용자가 위로 스크롤하지 않으면 overflow div를 맨 아래로 스크롤 한 상태로 유지
300 픽셀 크기의 div가 있고 페이지가 내용의 맨 아래로 스크롤 될 때 원합니다. 이 div에는 동적으로 콘텐츠가 추가되어 계속 스크롤되어 있어야합니다. 이제 사용자가 위로 스크롤하기로 결정한 경우 사용자가 다시 아래로 스크롤 할 때까지 맨 아래로 건너 뛰고 싶지 않습니다.
사용자가 위로 스크롤하지 않으면 사용자가 맨 아래로 스크롤하지 않으면 맨 아래로 스크롤 된 div를 가질 수 있습니까? 그리고 사용자가 맨 아래로 다시 스크롤하면 새로운 동적 내용이 추가 된 경우에도 맨 아래에 있어야합니다. 이것을 만들어내는 방법은 무엇입니까?
이것은 당신을 도울 수 있습니다 :
var element = document.getElementById("yourDivID");
element.scrollTop = element.scrollHeight;
[편집] 댓글과 일치합니다 ...
function updateScroll(){
var element = document.getElementById("yourDivID");
element.scrollTop = element.scrollHeight;
}
내용이 추가 될 때마다 updateScroll () 함수를 호출하거나 타이머를 설정하십시오.
//once a second
setInterval(updateScroll,1000);
사용자가 이동하지 않은 경우에만 업데이트하려는 경우 :
var scrolled = false;
function updateScroll(){
if(!scrolled){
var element = document.getElementById("yourDivID");
element.scrollTop = element.scrollHeight;
}
}
$("#yourDivID").on('scroll', function(){
scrolled=true;
});
방금 이것을 구현했으며 아마도 내 접근 방식을 사용할 수 있습니다.
다음 HTML이 있다고 가정 해보십시오.
<div id="out" style="overflow:auto"></div>
그런 다음 아래를 사용하여 맨 아래로 스크롤했는지 확인할 수 있습니다.
var out = document.getElementById("out");
// allow 1px inaccuracy by adding 1
var isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
scrollHeight 는 오버플로로 인해 보이지 않는 영역을 포함하여 요소의 높이를 제공합니다. clientHeight 는 CSS 높이를 제공하거나 다른 방법으로 요소의 실제 높이를 말합니다. 두 메소드는 모두없이 높이를 반환 margin
하므로 걱정할 필요가 없습니다. scrollTop 은 세로 스크롤의 위치를 제공합니다. 0은 상단이고 최대는 요소의 scrollHeight에서 요소 높이를 뺀 값입니다. 스크롤 막대를 사용할 때 스크롤 막대를 맨 아래로 내리는 것이 어려울 수 있습니다 (Chrome에서는 저에게 있습니다). 그래서 나는 1px 부정확성을 던졌습니다. 그래서 isScrolledToBottom
스크롤이 바닥에서 1 픽셀의 경우에도 마찬가지 일 것이다. 당신은 당신에게 맞는 느낌으로 이것을 설정할 수 있습니다.
그런 다음 단순히 요소의 scrollTop을 맨 아래로 설정하면됩니다.
if(isScrolledToBottom)
out.scrollTop = out.scrollHeight - out.clientHeight;
나는 당신이 개념을 보여주기 위해 바이올린을 만들었습니다 : http://jsfiddle.net/dotnetCarpenter/KpM5j/
편집 : 때 추가 된 코드는 명확히 isScrolledToBottom
이다 true
.
스크롤바를 아래로 붙입니다
const out = document.getElementById("out")
let c = 0
setInterval(function() {
// allow 1px inaccuracy by adding 1
const isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1
const newElement = document.createElement("div")
newElement.textContent = format(c++, 'Bottom position:', out.scrollHeight - out.clientHeight, 'Scroll position:', out.scrollTop)
out.appendChild(newElement)
// scroll to bottom if isScrolledToBottom is true
if (isScrolledToBottom) {
out.scrollTop = out.scrollHeight - out.clientHeight
}
}, 500)
function format () {
return Array.prototype.slice.call(arguments).join(' ')
}
#out {
height: 100px;
}
<div id="out" style="overflow:auto"></div>
<p>To be clear: We want the scrollbar to stick to the bottom if we have scrolled all the way down. If we scroll up, then we don't want the content to move.
</p>
CSS로만 작동하도록 할 수있었습니다.
트릭은 사용 display: flex;
하고flex-direction: column-reverse;
브라우저는 하단을 상단과 같이 취급합니다. 지원하는 브라우저를 지원한다고 가정하면 flex-box
유일한주의 사항은 마크 업이 역순이어야한다는 것입니다.
다음은 실제 예입니다. https://codepen.io/jimbol/pen/YVJzBg
$('#yourDiv').scrollTop($('#yourDiv')[0].scrollHeight);
라이브 데모 : http://jsfiddle.net/KGfG2/
$('#div1').scrollTop($('#div1')[0].scrollHeight);
Or animated:
$("#div1").animate({ scrollTop: $('#div1')[0].scrollHeight}, 1000);
$('#yourDivID').animate({ scrollTop: $(document).height() }, "slow");
return false;
This will calculate the ScrollTop Position from the height of #yourDivID
using the $(document).height()
property so that even if dynamic contents are added to the div the scroller will always be at the bottom position. Hope this helps. But it also has a small bug even if we scroll up and leaves the mouse pointer from the scroller it will automatically come to the bottom position. If somebody could correct that also it will be nice.
.cont{
height: 100px;
overflow-x: hidden;
overflow-y: auto;
transform: rotate(180deg);
direction:rtl;
text-align:left;
}
ul{
overflow: hidden;
transform: rotate(180deg);
}
<div class="cont">
<ul>
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</div>
Run code snippet
to see the effect. (PS: IfRun code snippet
is not working, try this: https://jsfiddle.net/Yeshen/xm2yLksu/3/ )How it work:
Default overflow is scroll from top to bottom.
transform: rotate(180deg)
can make it scroll or load dynamic block from bottom to top.
- Original idea:
https://blog.csdn.net/yeshennet/article/details/88880252
//Make sure message list is scrolled to the bottom
var container = $('#MessageWindowContent')[0];
var containerHeight = container.clientHeight;
var contentHeight = container.scrollHeight;
container.scrollTop = contentHeight - containerHeight;
Here is my version based on dotnetCarpenter's answer. My approach is a pure jQuery and I named the variables to make things a bit clearer.. What is happening is if the content height is greater then the container we scroll the extra distance down to achieve the desired result.
Works in IE and chrome..
Jim Hall's answer is preferrable because while it indeed does not scroll to the bottom when you're scrolled up, it is also pure CSS.
Very much unfortunately however, this is not a stable solution: In chrome (possibly due to the 1-px-issue described by dotnetCarpenter above), scrollTop
behaves inaccurately by 1 pixel, even without user interaction (upon element add). You can set scrollTop = scrollHeight - clientHeight
, but that will keep the div in position when another element is added, aka the "keep itself at bottom" feature is not working anymore.
So, in short, adding a small amount of Javascript (sigh) will fix this and fulfill all requirements:
Something like https://codepen.io/anon/pen/pdrLEZ this (example by Coo), and after adding an element to the list, also the following:
container = ...
if(container.scrollHeight - container.clientHeight - container.scrollTop <= 29) {
container.scrollTop = container.scrollHeight - container.clientHeight;
}
where 29 is the height of one line.
So, when the user scrolls up half a line (if that is even possible?), the Javascript will ignore it and scroll to the bottom. But I guess this is neglectible. And, it fixes the Chrome 1 px thingy.
Here's a solution based on a blog post by Ryan Hunt. It depends on the overflow-anchor
CSS property, which pins the scrolling position to an element at the bottom of the scrolled content.
const messages = [
'Expect rain today.',
'Tomorrow will be sunny.',
'Snow is coming next week.',
'Hailstorms are imminent.',
];
function addMessage() {
const $message = document.createElement('div');
$message.className = 'message';
$message.innerText = messages[(Math.random() * messages.length) | 0];
$messages.insertBefore($message, $anchor);
// Trigger the scroll pinning when the scroller overflows
if (!overflowing) {
overflowing = isOverflowing($scroller);
$scroller.scrollTop = $scroller.scrollHeight;
}
}
function isOverflowing($el) {
return $el.scrollHeight > $el.clientHeight;
}
const $scroller = document.querySelector('.scroller');
const $messages = document.querySelector('.messages');
const $anchor = document.querySelector('.anchor');
let overflowing = false;
setInterval(addMessage, 1000);
.scroller {
overflow: auto;
height: 90vh;
max-height: 11em;
background: #555;
}
.messages > * {
overflow-anchor: none;
}
.anchor {
overflow-anchor: auto;
height: 1px;
}
.message {
margin: .3em;
padding: .5em;
background: #eee;
}
<section class="scroller">
<div class="messages">
<div class="anchor"></div>
</div>
</section>
Note that overflow-anchor
doesn't currently work in Safari or Edge, so this solution doesn't currently work in all browsers.
Here is how I approached it. My div height is 650px. I decided that if the scroll height is within 150px of the bottom then auto scroll it. Else, leave it for the user.
if (container_block.scrollHeight - container_block.scrollTop < 800) {
container_block.scrollTo(0, container_block.scrollHeight);
}
'IT' 카테고리의 다른 글
C #과 .NET의 차이점은 무엇입니까? (0) | 2020.05.21 |
---|---|
SQL Server 2008의 쿼리 선택 결과에서 테이블을 만드는 방법 (0) | 2020.05.21 |
JavaScript에서 문자열 일치를위한 스위치 문 (0) | 2020.05.21 |
스도쿠 광장에서 볼록 결함을 제거하는 방법? (0) | 2020.05.21 |
프로그래밍 방식으로 EditText의 입력 유형을 PASSWORD에서 NORMAL로 또는 그 반대로 변경 (0) | 2020.05.21 |