JavaScript를 사용하여 요소까지 스크롤하려면 어떻게 해야 합니까?
를 이이 a a a a a a a a i로 합니다.<div>
★★★★★★ 。
다음 코드를 시도했지만 소용이 없었습니다.
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
ScrollIntoView는 정상적으로 동작합니다.
document.getElementById("divFirst").scrollIntoView();
앵커를 사용하여 div를 "포커스"할 수 있습니다.예:
<div id="myDiv"></div>
다음 javascript를 사용합니다.
// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";
Chrome 및 Firefox의 경우
나는 이것을 좀 조사해 보았고, 어떻게든 그것을 하는 가장 자연스러운 방법인 것 같은 것을 알아냈다.물론 지금은 개인적으로 가장 좋아하는 두루마리입니다.:)
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
IE, Edge 및 Safari 지원자용
:window.scroll({ ...options })
는 IE, Edge 및 Safari에서 지원되지 않습니다.이 경우 를 사용하는 것이 가장 좋습니다(IE 6에서 지원).대부분의 경우 부작용 없이 옵션을 전달할 수 있습니다(읽기: 테스트되지 않음).
물론 사용하는 브라우저에 따라 동작하는 기능으로 포장할 수 있습니다.
애니메이션 효과에도 효과가 있는 가장 짧은 답변:
var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});
고정식 네비게이션 바가 있는 경우 맨 위 값에서 높이를 빼면 고정식 바 높이가 70px인 경우 라인 2는 다음과 같습니다.
window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});
설명:라인 1은 요소 위치를 가져옵니다. 라인 2는 요소 위치로 스크롤합니다.behavior
효과를 .
3가지 방법으로 구현할 수 있습니다.
주의:
"자동 인식" => 특정 요소
"controllable-div" => 스크롤 가능 영역 div
방법 1:
document.querySelector('.automatic-scroll').scrollIntoView({
behavior: 'smooth'
});
방법 2:.
location.href = "#automatic-scroll";
방법 3:
$('#scrollable-div').animate({
scrollTop: $('#automatic-scroll').offset().top - $('#scrollable-div').offset().top +
$('#scrollable-div').scrollTop()
})
주의: 스크롤 가능한 영역 높이가 "auto"인 경우 방법 1 및 방법 2가 유용합니다.방법 3은 "calc(100vh - 200px)"와 같이 스크롤 가능한 영역 높이를 사용하는 경우에 유용합니다.
요소에 포커스를 설정할 수 있습니다., 보, 보, it, it, it, it, it, it보다 낫다scrollIntoView
node.setAttribute('tabindex', '-1')
node.focus()
node.removeAttribute('tabindex')
이것을 시험해 보세요.
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
예: @:
이러한 고정 헤더에 옵션 오프셋을 포함할 수 있는 함수가 있습니다.외부 라이브러리는 필요 없습니다.
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
JQuery를 사용하여 요소의 높이를 잡고 스크롤할 수 있습니다.
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
2018년 3월 갱신
JQuery를 사용하지 않고 이 답변으로 스크롤합니다.
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
특정 요소까지 스크롤하려면 이 javascript 전용 솔루션을 아래에 작성했습니다.
간단한 사용법:
EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
엔진 객체(필터, fps 값을 조작할 수 있음):
/**
*
* Created by Borbás Geri on 12/17/13
* Copyright (c) 2013 eppz! development, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
var EPPZScrollTo =
{
/**
* Helpers.
*/
documentVerticalScrollPosition: function()
{
if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
return 0; // None of the above.
},
viewportHeight: function()
{ return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },
documentHeight: function()
{ return (document.height !== undefined) ? document.height : document.body.offsetHeight; },
documentMaximumScrollPosition: function()
{ return this.documentHeight() - this.viewportHeight(); },
elementVerticalClientPositionById: function(id)
{
var element = document.getElementById(id);
var rectangle = element.getBoundingClientRect();
return rectangle.top;
},
/**
* Animation tick.
*/
scrollVerticalTickToPosition: function(currentPosition, targetPosition)
{
var filter = 0.2;
var fps = 60;
var difference = parseFloat(targetPosition) - parseFloat(currentPosition);
// Snap, then stop if arrived.
var arrived = (Math.abs(difference) <= 0.5);
if (arrived)
{
// Apply target.
scrollTo(0.0, targetPosition);
return;
}
// Filtered position.
currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);
// Apply target.
scrollTo(0.0, Math.round(currentPosition));
// Schedule next tick.
setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
},
/**
* For public use.
*
* @param id The id of the element to scroll to.
* @param padding Top padding to apply above element.
*/
scrollVerticalToElementById: function(id, padding)
{
var element = document.getElementById(id);
if (element == null)
{
console.warn('Cannot find element with id \''+id+'\'.');
return;
}
var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
var currentPosition = this.documentVerticalScrollPosition();
// Clamp.
var maximumScrollPosition = this.documentMaximumScrollPosition();
if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;
// Start animation.
this.scrollVerticalTickToPosition(currentPosition, targetPosition);
}
};
@caveman의 솔루션과 유사
const element = document.getElementById('theelementsid');
if (element) {
window.scroll({
top: element.scrollTop,
behavior: 'smooth',
})
}
용기를 내용물까지 스크롤할 때 자주 사용하는 방법입니다.
/**
@param {HTMLElement} container : element scrolled.
@param {HTMLElement} target : element where to scroll.
@param {number} [offset] : scroll back by offset
*/
var scrollAt=function(container,target,offset){
if(container.contains(target)){
var ofs=[0,0];
var tmp=target;
while (tmp!==container) {
ofs[0]+=tmp.offsetWidth;
ofs[1]+=tmp.offsetHeight;
tmp=tmp.parentNode;
}
container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
}else{
throw('scrollAt Error: target not found in container');
}
};
글로벌하게 덮어쓰기를 원하는 경우 다음 작업을 수행할 수도 있습니다.
HTMLElement.prototype.scrollAt=function(target,offset){
if(this.contains(target)){
var ofs=[0,0];
var tmp=target;
while (tmp!==this) {
ofs[0]+=tmp.offsetWidth;
ofs[1]+=tmp.offsetHeight;
tmp=tmp.parentNode;
}
container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
}else{
throw('scrollAt Error: target not found in container');
}
};
대화식 요소에만 포커스를 설정할 수 있습니다...Div는 페이지의 논리 섹션만 나타냅니다.
div의 테두리를 설정하거나 div의 색상을 변경하여 포커스를 시뮬레이트할 수 있습니다.그리고 네, 가시성은 초점이 아닙니다.
div에 tabindex를 추가하면 포커스를 얻을 수 있다고 생각합니다.
<div class="divFirst" tabindex="-1">
</div>
tabindex는 a, area, button, input, object, select, text area에만 적용할 수 있다고 생각하지 않습니다.하지만 한번 시도해 보세요.
동작으로 인해 Safari, Safari ios, Explorer에서는 "smooth"가 작동하지 않습니다.보통 request Animation Frame을 이용하여 간단한 함수를 씁니다.
(function(){
var start;
var startPos = 0;
//Navigation scroll page to element
function scrollTo(timestamp, targetTop){
if(!start) start = timestamp
var runtime = timestamp - start
var progress = Math.min(runtime / 700, 1)
window.scroll(0, startPos + (targetTop * progress) )
if(progress >= 1){
return;
}else {
requestAnimationFrame(function(timestamp){
scrollTo(timestamp, targetTop)
})
}
};
navElement.addEventListener('click', function(e){
var target = e.target //or this
var targetTop = _(target).getBoundingClientRect().top
startPos = window.scrollY
requestAnimationFrame(function(timestamp){
scrollTo(timestamp, targetTop)
})
}
})();
div에 집중하면 안 돼요.이 div의 입력 요소에만 초점을 맞출 수 있습니다.또한 요소를 사용해야 합니다.display() 대신 focus()를 사용합니다.
여러 번 둘러본 결과, 드디어 이렇게 되었습니다.
스크롤 막대가 있는 돔에서 div를 찾거나 위치를 지정합니다.저는 "div class="table_body table_body_div" scroll_top="0" scroll_left="0" style="width: 1263px;높이: 499px;"와 같이 보입니다.
xpath : //div [@class='table_body table_body_div']를 사용하여 검색했습니다.
JavaScript를 사용하여 다음과 같이 스크롤 실행 : (Javascript)실행자) 드라이버).executeScript("arguments[0].scrollLLeft = 인수[1];, executeScript, 2000);
2000은 오른쪽으로 스크롤하고 싶은 픽셀의 수입니다.div를 아래로 스크롤하려면 scroll Left 대신 scroll Top을 사용합니다.
메모: ScrollIntoView를 사용해 봤는데 웹페이지에 여러 개의 DIV가 있어서 제대로 작동하지 않았습니다.포커스가 있는 메인창이 1개만 있으면 동작합니다.만약 당신이 내가 원하지 않았던 jQuery를 사용하고 싶지 않다면, 이것이 내가 찾은 최고의 해결책이다.
html 을 사용하고 싶은 경우는, 다음과 같이 사용할 수 있습니다.
a href="samplewebsite.com/subdivision.html#id
특정 요소 ID에 대한 html 링크로 만듭니다.기본적으로는getElementById
html 버전
Jquery 솔루션:
$("#divFirst")[0].scrollIntoView();
이 기능을 시험해 보다
function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}
div ID를 매개 변수로 전달합니다. 작동됩니다. 이미 사용 중입니다.
언급URL : https://stackoverflow.com/questions/5007530/how-do-i-scroll-to-an-element-using-javascript
'programing' 카테고리의 다른 글
Galera MySQL의 추가 노드 추가 실패 (0) | 2022.09.21 |
---|---|
Tymeleaf: 조건을 사용하여 CSS 클래스를 동적으로 추가/삭제하는 방법 (0) | 2022.09.21 |
Node.js 스트림의 내용을 문자열 변수로 읽으려면 어떻게 해야 합니까? (0) | 2022.09.21 |
명령줄에서 외부 키 검사 비활성화 (0) | 2022.09.21 |
Python에서 오브젝트의 크기를 확인하는 방법은 무엇입니까? (0) | 2022.09.21 |