HTML 페이지를 지정된 앵커로 스크롤하는 방법
JavaScript를 사용하는 것만으로 특정 앵커까지 페이지를 스크롤 할 수 있는 브라우저를 만들고 싶습니다.
지지 a a a a 를 했습니다.name
★★★★★★★★★★★★★★★★★」id
HTML 드 html :
<a name="anchorName">..</a>
또는
<h1 id="anchorName2">..</h1>
같은 http://server.com/path#anchorName
의 맨 합니다 앵커가 페이지의 보이는 부분 위에 오도록 페이지를 스크롤해야 합니다.
function scrollTo(hash) {
location.hash = "#" + hash;
}
jQuery는 전혀 필요 없습니다!
매우 심플:
var element_to_scroll_to = document.getElementById('anchorName2');
// Or:
var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
// Or:
var element_to_scroll_to = $('.my-element-class')[0];
// Basically `element_to_scroll_to` just have to be a reference
// to any DOM element present on the page
// Then:
element_to_scroll_to.scrollIntoView();
jQuery의 .animate(), .offset() 및scrollTop
를 들면
$(document.body).animate({
'scrollTop': $('#anchorName2').offset().top
}, 2000);
링크 예: http://jsbin.com/unasi3/edit
애니메이션을 하지 않으면 다음과 같이 .scrollTop()을 사용합니다.
$(document.body).scrollTop($('#anchorName2').offset().top);
JavaScript의 인 JavaScript 네 or or or orlocation.hash
들면 다음과 같습니다.
location.hash = '#' + anchorid;
2018-2020 순수 자바스크립트:
요소로 스크롤하는 매우 편리한 방법이 있습니다.
el.scrollIntoView({
behavior: 'smooth', // smooth scroll
block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})
하지만 제가 알기론 아래 옵션만큼 좋은 지원은 없는 것으로 알고 있습니다.
요소가 맨 위에 있어야 하는 경우:
const element = document.querySelector('#element')
const topPos = element.getBoundingClientRect().top + window.pageYOffset
window.scrollTo({
top: topPos, // scroll so that the element is at the top of the view
behavior: 'smooth' // smooth scroll
})
요소를 중앙에 배치하려면 다음 절차를 수행합니다.
const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
window.scroll({
top: rect.top + rect.height / 2 - viewHeight / 2,
behavior: 'smooth' // smooth scroll
});
지원:
저것은 고있 that that that라고 .scroll
와 같은 방법입니다.scrollTo
은 , , , , 에서 더 잘 .scrollTo
.
방법에 대한 자세한 정보
jandy의 훌륭한 솔루션이지만, 부드러운 스크롤이 Firefox에서 동작하는 데 문제가 있는 것 같습니다.
Firefox에서도 이 방법으로 쓸 수 있습니다.
(function($) {
$(document).ready(function() {
$('html, body').animate({
'scrollTop': $('#anchorName2').offset().top
}, 2000);
});
})(jQuery);
다음은 jQuery를 사용하지 않는 순수 자바스크립트 솔루션입니다.Chrome과 Internet Explorer에서 테스트되었지만 iOS에서는 테스트되지 않았습니다.
function ScrollTo(name) {
ScrollToResolver(document.getElementById(name));
}
function ScrollToResolver(elem) {
var jump = parseInt(elem.getBoundingClientRect().top * .2);
document.body.scrollTop += jump;
document.documentElement.scrollTop += jump;
if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
elem.lastjump = Math.abs(jump);
setTimeout(function() { ScrollToResolver(elem);}, "100");
} else {
elem.lastjump = null;
}
}
데모: https://jsfiddle.net/jd7q25hg/12/
2018년에는 이와 같은 간단한 작업에 jQuery가 필요하지 않습니다.빌트인 메서드는 "behavior
페이지상의 임의의 요소로 부드럽게 스크롤 할 수 있는 속성.브라우저 URL을 해시로 업데이트하여 북마크할 수도 있습니다.
HTML 북마크 스크롤에 대한 이 튜토리얼에서는 페이지의 모든 앵커 링크에 자동으로 부드러운 스크롤을 추가하는 방법을 설명합니다.
let anchorlinks = document.querySelectorAll('a[href^="#"]')
for (let item of anchorlinks) { // relitere
item.addEventListener('click', (e)=> {
let hashval = item.getAttribute('href')
let target = document.querySelector(hashval)
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
})
history.pushState(null, null, hashval)
e.preventDefault()
})
}
은 '앵커'를 추가하는 입니다.*{scroll-behavior: smooth;}
당신의 style.css 파일과 HTML 네비게이션 사용으로#NameOfTheSection
.
*{scroll-behavior: smooth;}
<a href="#scroll-to">Click to Scroll<a/>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<section id="scroll-to">
<p>it will scroll down to this section</p>
</section>
적절한 위치까지 부드럽게 스크롤
맞히다 y
조정하여 사용하다
const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;
window.scrollTo({top: y, behavior: 'smooth'});
$(document).ready ->
$("a[href^='#']").click ->
$(document.body).animate
scrollTop: $($(this).attr("href")).offset().top, 1000
CSS-Tricks의 솔루션은 jQuery 2.2.0에서 동작하지 않게 되었습니다.셀렉터 에러가 발생합니다.
JavaScript 런타임 오류: 구문 오류, 인식할 수 없는 식: a [href*=#]:not([href=#])
셀렉터를 바꿔서 고쳤어요.전체 스니펫은 다음과 같습니다.
$(function() {
$("a[href*='#']:not([href='#'])").click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
이 방법은 다음과 같습니다.
$('.scroll').on("click", function(e) {
e.preventDefault();
var dest = $(this).attr("href");
$("html, body").animate({
'scrollTop': $(dest).offset().top
}, 2000);
});
https://jsfiddle.net/68pnkfgd/
애니메이션을 수행할 링크에 클래스 'scroll'을 추가합니다.
대부분의 답은 불필요하게 복잡하다.
타겟 요소로 점프하고 싶은 경우 JavaScript는 필요 없습니다.
# the link:
<a href="#target">Click here to jump.</a>
# target element:
<div id="target">Any kind of element.</div>
타겟까지 애니메이션으로 스크롤 하려면 5hahiL의 답변을 참조해 주세요.
jQuery("a[href^='#']").click(function(){
jQuery('html, body').animate({
scrollTop: jQuery( jQuery(this).attr('href') ).offset().top
}, 1000);
return false;
});
이 스크립트는 페이지를 앵커까지 스크롤하는 작업 스크립트입니다.이를 설정하려면 스크롤할 앵커의 이름 속성과 일치하는 ID를 앵커링크에 지정하기만 하면 됩니다.
<script>
jQuery(document).ready(function ($){
$('a').click(function (){
var id = $(this).attr('id');
console.log(id);
if ( id == 'cet' || id == 'protein' ) {
$('html, body').animate({ scrollTop: $('[name="' + id + '"]').offset().top}, 'slow');
}
});
});
</script>
CSS-Tricks에서 쉽고 간단한 jQuery 솔루션을 찾았습니다.그게 내가 지금 쓰고 있는 거야.
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Vue.js 2 솔루션에서는 간단한 데이터 속성을 추가하여 업데이트를 강제합니다.
const app = new Vue({
...
, updated: function() {
this.$nextTick(function() {
var uri = window.location.href
var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
this.updater = "" // only on page-load !
location.href = "#"+String(anchor)
}
})
}
});
app.updater = "page_load"
/* Smooth scrolling in CSS - it works in HTML5 only */
html, body {
scroll-behavior: smooth;
}
언급URL : https://stackoverflow.com/questions/3163615/how-to-scroll-an-html-page-to-a-given-anchor
'programing' 카테고리의 다른 글
Maven 2에서는 어떤 종속성이 경과적 종속성인지 어떻게 알 수 있습니까? (0) | 2022.09.19 |
---|---|
자바에서 정수 나눗셈을 반올림하여 int 결과를 얻는 방법 (0) | 2022.09.19 |
데이터베이스에 IP를 저장하는 가장 좋은 방법? (0) | 2022.09.19 |
AWS RDS MariaDB 용량 계획 (0) | 2022.09.18 |
라이브러리를 사용하지 않고 jwt 토큰을 javascript로 디코딩하는 방법은 무엇입니까? (0) | 2022.09.18 |