페이지 맨 아래까지 자동으로 스크롤
질문 목록이 있습니다.첫 번째 질문을 클릭하면 자동으로 페이지 하단의 특정 요소로 이동합니다.
jQuery에서 이 작업을 수행하려면 어떻게 해야 합니까?
jQuery는 필요 없습니다.구글 검색에서 얻은 상위 검색 결과는 대부분 다음과 같습니다.
window.scrollTo(0, document.body.scrollHeight);
중첩된 요소가 있는 경우 문서가 스크롤되지 않을 수 있습니다.이 경우 스크롤하는 요소를 대상으로 하고 스크롤 높이를 사용해야 합니다.
window.scrollTo(0, document.querySelector(".scrollingContainer").scrollHeight);
을 거에 the the에 묶을 수 .onclick
예 질의이이예예예예예예예예예예예:<div onclick="ScrollToBottom()" ...
를 참조해 주세요.
다음 추가 소스를 참조할 수 있습니다.
- http://www.sourcetricks.com/2010/07/javascript-scroll-to-bottom-of-page.html
- http://www.alecjacobson.com/weblog/?p=753
- http://www.mediacollege.com/internet/javascript/page/scroll.html
- http://www.electrictoolbox.com/jquery-scroll-bottom/
페이지 전체를 아래로 스크롤하려면:
const scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;
데모는 이쪽에서 보실 수 있습니다.
특정 요소를 아래로 스크롤하려면:
const scrollToBottom = (id) => {
const element = document.getElementById(id);
element.scrollTop = element.scrollHeight;
}
여기 데모입니다.
작동 방식은 다음과 같습니다.
참조: scroll Top, scroll Height, 클라이언트높이
업데이트: Chrome(61+) 및 Firefox의 최신 버전은 본문 스크롤을 지원하지 않습니다. https://dev.opera.com/articles/fixing-the-scrolltop-bug/를 참조하십시오.
Vanilla JS 구현:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
이를 사용하여 페이지를 애니메이션 형식으로 내려갈 수 있습니다.
$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");
크로스 브라우저 솔루션은 다음과 같습니다.Chrome, Firefox, Safari 및 IE11에서 테스트 완료
window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
window.scrollTo(0, document.body.scrollHeight), Firefox 37.0.2 이상에서는 동작하지 않습니다.
아래로 스크롤을 부드럽게 하기 위한 라이너 1개
window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });
업 하려면 , 「 」를 만 하면 됩니다.top
로로 합니다.0
페이지가 끝까지 스크롤하여(예를 들어 소셜 네트워크) 버텀으로 확장되는 경우가 있습니다(페이지의 최종 버텀).다음 스크립트를 사용합니다.
var scrollInterval = setInterval(function() {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);
브라우저의 javascript 콘솔에 있는 경우 스크롤을 정지하는 것이 도움이 될 수 있으므로 다음과 같이 추가합니다.
var stopScroll = function() { clearInterval(scrollInterval); };
다음에 and고 and and를 사용합니다.stopScroll();
.
특정 요소로 스크롤해야 할 경우 다음을 사용합니다.
var element = document.querySelector(".element-selector");
element.scrollIntoView();
또는 특정 요소에 대한 자동 스크롤(또는 페이지 스크롤 간격 중지)을 위한 범용 스크립트:
var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
var element = document.querySelector(".element-selector");
if (element) {
// element found
clearInterval(scrollInterval);
element.scrollIntoView();
} else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) {
// no element -> scrolling
notChangedStepsCount = 0;
document.documentElement.scrollTop = document.documentElement.scrollHeight;
} else if (notChangedStepsCount > 20) {
// no more space to scroll
clearInterval(scrollInterval);
} else {
// waiting for possible extension (autoload) of the page
notChangedStepsCount++;
}
}, 50);
CSS만?!
대상 CSS만의 대체 수단:
display: flex;
flex-direction: column-reverse;
/* ...probably usually along with: */
overflow-y: scroll; /* or hidden or auto */
height: 100px; /* or whatever */
방탄은 아니지만 몇 가지 상황에서 도움이 된다는 것을 알게 되었습니다.
문서: , ,
데모:
var i=0, foo='Lorem Ipsum & foo in bar or blah ! on and'.split(' ');
setInterval(function(){demo.innerHTML+=foo[i++%foo.length]+' '},200)
#demo{ display:flex;
flex-direction:column-reverse;
overflow-y:scroll;
width:150px;
height:150px;
border:3px solid black; }
body{ font-family:arial,sans-serif;
font-size:15px; }
Autoscrolling demo:🐾
<div id='demo'></div>
이 함수는 필요한 장소에서 사용할 수 있습니다.
function scroll_to(div){
if (div.scrollTop < div.scrollHeight - div.clientHeight)
div.scrollTop += 10; // move down
}
애니메이션으로도 할 수 있습니다. 매우 간단합니다.
$('html, body').animate({
scrollTop: $('footer').offset().top
//scrollTop: $('#your-id').offset().top
//scrollTop: $('.your-class').offset().top
}, 'slow');
희망은 도움이 된다, 고마워
답장이 너무 많아서 문서의 높이를 계산하려고 합니다.하지만 그것은 나에게 정확하게 계산되지 않았다.그러나 이 두 가지 모두 효과가 있었습니다.
쿼리
$('html,body').animate({scrollTop: 9999});
또는 js만
window.scrollTo(0,9999);
특정 요소까지 스크롤 다운하는 간단한 방법입니다.
아래로 스크롤하고 싶을 때마다 이 함수를 호출합니다.
function scrollDown() {
document.getElementById('scroll').scrollTop = document.getElementById('scroll').scrollHeight
}
ul{
height: 100px;
width: 200px;
overflow-y: scroll;
border: 1px solid #000;
}
<ul id='scroll'>
<li>Top Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Bottom Here</li>
<li style="color: red">Bottom Here</li>
</ul>
<br />
<button onclick='scrollDown()'>Scroll Down</button>
다음은 나에게 효과가 있었던 방법입니다.
예상 결과:
- 스크롤 애니메이션 없음
- 첫 번째 로드 시 페이지 하단에 로드
- 모든 갱신을 위해 페이지 하단에 로드
코드:
<script>
function scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
history.scrollRestoration = "manual";
window.onload = scrollToBottom;
</script>
이것이 다른 방법으로 동작하는 이유:
Chrome과 같은 브라우저에는 새로 고침 후 페이지 상의 위치를 기억하기 위한 사전 설정이 내장되어 있습니다....window.onload
다음과 같은 회선을 호출한 후 브라우저가 자동으로 새로 고치기 전의 위치로 스크롤하기 때문에 작동하지 않습니다.
window.scrollTo(0, document.body.scrollHeight);
그렇기 때문에 다음 사항을 추가해야 합니다.
history.scrollRestoration = "manual";
before window.onload
기본 제공 기능을 비활성화합니다.
참고 자료:
『 』의 매뉴얼:
window.onload
: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
『 』의 매뉴얼:
window.scrollTo
: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
『 』의 매뉴얼:
history.scrollRestoration
: https://developer.mozilla.org/en-US/docs/Web/API/History/scrollRestoration
젠틀 앵커에게 멋진 Javascript 플러그인을 시험해 보세요.
예:
function SomeFunction() {
// your code
// Pass an id attribute to scroll to. The # is required
Gentle_Anchors.Setup('#destination');
// maybe some more code
}
테스트 대상 호환성:
- Mac Firefox, Safari, Opera
- Windows Firefox, Opera, Safari, Internet Explorer 5.55 이상
- Linux는 테스트되지 않았지만 최소한 Firefox에서는 문제가 없습니다.
것도 수 요.id
을 href
'이것'은 다음과 같습니다.
<a href="#myLink" id="myLink">
Click me
</a>
가 를 클릭했을 때Click me
에서 네비게이션은 ""로 합니다.Click me
그 자체입니다.
파티에는 늦었지만, 여기 어떤 요소든 아래로 스크롤할 수 있는 간단한 Javascript 전용 코드가 있습니다.
function scrollToBottom(e) {
e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}
셀레늄에서 아래로 스크롤하려면 아래 코드를 사용합니다.
맨 아래까지 페이지 높이까지 스크롤합니다.JavaScript와 React에서 모두 정상적으로 동작하는 아래의 Javascript 코드를 사용합니다.
JavascriptExecutor jse = (JavascriptExecutor) driver; // (driver is your browser webdriver object)
jse.executeScript("window.scrollBy(0,document.body.scrollHeight || document.documentElement.scrollHeight)", "");
제 해결책은 다음과 같습니다.
//**** scroll to bottom if at bottom
function scrollbottom() {
if (typeof(scr1)!='undefined') clearTimeout(scr1)
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
if((scrollTop + window.innerHeight) >= scrollHeight-50) window.scrollTo(0,scrollHeight+50)
scr1=setTimeout(function(){scrollbottom()},200)
}
scr1=setTimeout(function(){scrollbottom()},200)
저는 역동적인 콘텐츠를 가진 Angular 앱을 가지고 있는데, 위의 답변 중 몇 가지를 시도해 봤지만 그다지 성공적이지 않았습니다.저는 @Konard의 답변을 수정하여 시나리오에 맞게 플레인 JS로 작업했습니다.
HTML
<div id="app">
<button onClick="scrollToBottom()">Scroll to Bottom</button>
<div class="row">
<div class="col-md-4">
<br>
<h4>Details for Customer 1</h4>
<hr>
<!-- sequence Id -->
<div class="form-group">
<input type="text" class="form-control" placeholder="ID">
</div>
<!-- name -->
<div class="form-group">
<input type="text" class="form-control" placeholder="Name">
</div>
<!-- description -->
<div class="form-group">
<textarea type="text" style="min-height: 100px" placeholder="Description" ></textarea>
</div>
<!-- address -->
<div class="form-group">
<input type="text" class="form-control" placeholder="Address">
</div>
<!-- postcode -->
<div class="form-group">
<input type="text" class="form-control" placeholder="Postcode">
</div>
<!-- Image -->
<div class="form-group">
<img style="width: 100%; height: 300px;">
<div class="custom-file mt-3">
<label class="custom-file-label">{{'Choose file...'}}</label>
</div>
</div>
<!-- Delete button -->
<div class="form-group">
<hr>
<div class="row">
<div class="col">
<button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to save">Save</button>
<button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to update">Update</button>
</div>
<div class="col">
<button class="btn btn-danger btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to remove">Remove</button>
</div>
</div>
<hr>
</div>
</div>
</div>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
JS
function scrollToBottom() {
scrollInterval;
stopScroll;
var scrollInterval = setInterval(function () {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);
var stopScroll = setInterval(function () {
clearInterval(scrollInterval);
}, 100);
}
최신 Chrome, FF, Edge 및 Stock Android 브라우저에서 테스트.여기 바이올린이 있습니다.
https://jsfiddle.net/cbruen1/18cta9gd/16/
나는 그것을 실현시킬 수 있는 방법을 찾았다.
페이지 하단에 입력 유형 텍스트를 배치하고 맨 아래에 필요할 때마다 jquery focus를 호출합니다.
테두리와 배경을 클리어하기 위해 읽기 전용으로 멋진 css로 만듭니다.
Angular를 찾는 사람이 있다면
아래로 스크롤하면 div에 추가할 수 있습니다.
#scrollMe [scrollTop]="scrollMe.scrollHeight"
<div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
</div>
이렇게 하면 맨 아래로 스크롤됩니다.
헤드 코드
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script language="javascript" type="text/javascript">
function scrollToBottom() {
$('#html, body').scrollTop($('#html, body')[0].scrollHeight);
}
</script>
본문코드
<a href="javascript:void(0);" onmouseover="scrollToBottom();" title="Scroll to Bottom">▼ Bottom ▼</a>
저도 같은 문제가 있었어요.한때 div의 요소가 완전히 로드되지 않았고 scrollTop 속성이 현재 값인 scrollHeight로 초기화되었습니다.이것은 scrollHeight의 올바른 끝값이 아닙니다.
내 프로젝트는 Angular 8이고 내가 한 일은:
- .ts 파일의 요소를 얻기 위해 viewchild를 사용했습니다.
- AfterViewChecked 이벤트를 상속하고 여기에 viewchild 요소가 scrollHeight 값(this.viewChildElement.nativeElement.scrollTop = this)을 고려해야 함을 나타내는 코드 한 줄을 배치했습니다.viewChildElement.nativeElement.scrollHeight;)
AfterViewChecked 이벤트는 여러 번 발생하며 최종적으로 스크롤 높이에서 적절한 값을 가져옵니다.
ref 및 getElementById를 사용하여 특정 모달 또는 페이지를 스크롤할 수 있습니다.
const scrollToBottomModel = () => {
const scrollingElement = document.getElementById("post-chat");
scrollingElement.scrollTop = scrollingElement.scrollHeight;
};
모달 바디에서는 위의 함수를 호출할 수 있습니다.
<Modal.Body
className="show-grid"
scrollable={true}
style={{
maxHeight: "calc(100vh - 210px)",
overflowY: "auto",
height: "590px",
}}
ref={input => scrollToBottomModel()}
id="post-chat"
>
이거면 될 거야
jquery를 사용한 간단한 예
$('html, body').animate({
scrollTop: $(this).height(),
});
스크롤토는 포기하고 앵커 어프로치를 시도했습니다.
<a href="#target_id_at_bottom">scroll to the bottom</a>
이 CSS의 매력과 함께:
html,
body {
scroll-behavior: smooth;
}
좋은 하루 보내세요!
window.scrollTo(0,1e10);
항상 동작합니다.
1e10은 큰 숫자입니다.그래서 항상 페이지 끝이에요.
천 마디 말보다 한 장의 사진이 더 낫다.
요점은 다음과 같습니다.
document.documentElement.scrollTo({
left: 0,
top: document.documentElement.scrollHeight - document.documentElement.clientHeight,
behavior: 'smooth'
});
사용하고 있다document.documentElement
,, , 。<html>
아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 맞다.window
제인 취향입니다. 전체가 입니다. 페이지 전체가 아니라 컨테이너일 경우 이렇게 동작하기 때문입니다.단, 변경되는 것을 제외합니다.document.body
그리고.document.documentElement
로.document.querySelector("#container-id")
.
예:
let cLines = 0;
let timerID = setInterval(function() {
let elSomeContent = document.createElement("div");
if (++cLines > 33) {
clearInterval(timerID);
elSomeContent.innerText = "That's all folks!";
} else {
elSomeContent.innerText = new Date().toLocaleDateString("en", {
dateStyle: "long",
timeStyle: "medium"
});
}
document.body.appendChild(elSomeContent);
document.documentElement.scrollTo({
left: 0,
top: document.documentElement.scrollHeight - document.documentElement.clientHeight,
behavior: 'smooth'
});
}, 1000);
body {
font: 27px Arial, sans-serif;
background: #ffc;
color: #333;
}
없는 경우 차이를 비교할 수 있습니다.scrollTo()
:
let cLines = 0;
let timerID = setInterval(function() {
let elSomeContent = document.createElement("div");
if (++cLines > 33) {
clearInterval(timerID);
elSomeContent.innerText = "That's all folks!";
} else {
elSomeContent.innerText = new Date().toLocaleDateString("en", {
dateStyle: "long",
timeStyle: "medium"
});
}
document.body.appendChild(elSomeContent);
}, 1000);
body {
font: 27px Arial, sans-serif;
background: #ffc;
color: #333;
}
언급URL : https://stackoverflow.com/questions/11715646/scroll-automatically-to-the-bottom-of-the-page
'programing' 카테고리의 다른 글
루트 비밀번호를 null로 설정하는 방법 (0) | 2022.09.08 |
---|---|
MariaDB/MySQL RANK() 구현 (0) | 2022.09.08 |
MariaDB: ALTER TABLE 구문을 사용하여 외부 키를 추가하시겠습니까? (0) | 2022.09.08 |
i++는 스레드가 안전하지 않다고 들었는데, ++i 스레드는 안전한가요? (0) | 2022.09.02 |
Java에서 final로 선언된 문자열과 == 비교 (0) | 2022.09.02 |