jQuery를 사용하여 페이지를 앵커로 스크롤하는 방법은 무엇입니까?
페이지의 위 또는 아래에서 로컬 앵커에 대한 링크를 클릭 할 때 슬라이드 효과를 포함시키는 방법을 찾고 있습니다.
나는 당신이 그렇게 링크가있는 것을 원합니다 :
<a href="#nameofdivetc">link text, img etc.</a>
아마도 클래스가 추가 되었으므로이 링크가 슬라이딩 링크가되고 싶다는 것을 알 수 있습니다.
<a href="#nameofdivetc" class="sliding-link">link text, img etc.</a>
그런 다음이 링크를 클릭하면 페이지가 필요한 위치 (div, 제목, 페이지 상단 등)로 위 또는 아래로 슬라이드됩니다.
이것이 내가 이전에했던 것입니다 :
$(document).ready(function(){
$(".scroll").click(function(event){
//prevent the default action for the click event
event.preventDefault();
//get the full url - like mysitecom/index.htm#home
var full_url = this.href;
//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
var parts = full_url.split("#");
var trgt = parts[1];
//get the top offset of the target anchor
var target_offset = $("#"+trgt).offset();
var target_top = target_offset.top;
//goto that anchor by setting the body scroll top to anchor top
$('html, body').animate({scrollTop:target_top}, 1500, 'easeInSine');
});
});
기술
jQuery.offset()
및을 사용하여이 작업을 수행 할 수 있습니다 jQuery.animate()
.
jsFiddle Demonstration을 확인하십시오 .
견본
function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top},'slow');
}
scrollToAnchor('id3');
추가 정보
href 속성이 동일한 이름을 가진 태그 ID를 가진 div에 연결 한다고 가정하면 다음 코드를 사용할 수 있습니다.
HTML
<a href="#goto" class="sliding-link">Link to div</a>
<div id="goto">I'm the div</div>
자바 스크립트-(Jquery)
$(".sliding-link").click(function(e) {
e.preventDefault();
var aid = $(this).attr("href");
$('html,body').animate({scrollTop: $(aid).offset().top},'slow');
});
이것은 내 인생을 훨씬 쉽게 만들었습니다. 기본적으로 요소 id 태그와 많은 코드없이 스크롤합니다.
http://balupton.github.io/jquery-scrollto/
자바 스크립트에서
$('#scrollto1').ScrollTo();
귀하의 HTML에서
<div id="scroollto1">
여기에 나는 페이지 끝까지
function scroll_to_anchor(anchor_id){
var tag = $("#"+anchor_id+"");
$('html,body').animate({scrollTop: tag.offset().top},'slow');
}
또한 대상에 패딩이 있으므로 position
대신 을 사용하는 것을 고려해야합니다 offset
. 대상과 겹치지 않으려는 잠재적 탐색 모음을 설명 할 수도 있습니다.
const $navbar = $('.navbar');
$('a[href^="#"]').on('click', function(e) {
e.preventDefault();
const scrollTop =
$($(this).attr('href')).position().top -
$navbar.outerHeight();
$('html, body').animate({ scrollTop });
})
나는 원래 코드를 고수 하고이 코드를 사용하는 'back-to-top'링크에 페이드를 포함했으며 여기에서도 약간의 코드를 사용했습니다.
http://webdesignerwall.com/tutorials/animated-scroll-to-top
잘 작동합니다 :)
jQuery를 사용한 나의 접근 방식은 모든 임베디드 앵커 링크를 즉시 점프하는 대신 슬라이드하게 만듭니다.
Santi Nunez 의 답변과 실제로 비슷 하지만 더 안정적 입니다.
지원하다
- 다중 프레임 워크 환경.
- 페이지로드가 완료되기 전에
<a href="#myid">Go to</a>
<div id="myid"></div>
// Slow scroll with anchors
(function($){
$(document).on('click', 'a[href^=#]', function(e){
e.preventDefault();
var id = $(this).attr('href');
$('html,body').animate({scrollTop: $(id).offset().top}, 500);
});
})(jQuery);
전체 페이지가 아니라 중첩 된 내용을 애니메이션하는 경우 offsetTop 및 scrollTop 값 을 추가 할 수 있습니다 .
예 :
var itemTop= $('.letter[name="'+id+'"]').offset().top;
var offsetTop = $someWrapper.offset().top;
var scrollTop = $someWrapper.scrollTop();
var y = scrollTop + letterTop - offsetTop
this.manage_list_wrap.animate({
scrollTop: y
}, 1000);
SS 슬로우 스크롤
이 솔루션에는 앵커 태그가 필요하지 않지만 물론 메뉴 버튼 (예 : 임의 속성, 'ss')을 HTML의 대상 요소 ID와 일치시켜야합니다.
ss="about"
당신을 데려다 id="about"
$('.menu-item').click(function() {
var keyword = $(this).attr('ss');
var scrollTo = $('#' + keyword);
$('html, body').animate({
scrollTop: scrollTo.offset().top
}, 'slow');
});
.menu-wrapper {
display: flex;
margin-bottom: 500px;
}
.menu-item {
display: flex;
justify-content: center;
flex: 1;
font-size: 20px;
line-height: 30px;
color: hsla(0, 0%, 80%, 1);
background-color: hsla(0, 0%, 20%, 1);
cursor: pointer;
}
.menu-item:hover {
background-color: hsla(0, 40%, 40%, 1);
}
.content-block-header {
display: flex;
justify-content: center;
font-size: 20px;
line-height: 30px;
color: hsla(0, 0%, 90%, 1);
background-color: hsla(0, 50%, 50%, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="menu-wrapper">
<div class="menu-item" ss="about">About Us</div>
<div class="menu-item" ss="services">Services</div>
<div class="menu-item" ss="contact">Contact</div>
</div>
<div class="content-block-header" id="about">About Us</div>
<div class="content-block">
Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.
That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>
<div class="content-block-header" id="services">Services</div>
<div class="content-block">
Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.
That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>
<div class="content-block-header" id="contact">Contact</div>
<div class="content-block">
Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.
That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>
깡깡이
https://jsfiddle.net/Hastig/stcstmph/4/
Here is the solution that worked for me. This is a generic function which works for all of the a
tags referring to a named a
$("a[href^=#]").on('click', function(event) {
event.preventDefault();
var name = $(this).attr('href');
var target = $('a[name="' + name.substring(1) + '"]');
$('html,body').animate({ scrollTop: $(target).offset().top }, 'slow');
});
Note 1: Make sure that you use double quotes "
in your html. If you use single quotes, change the above part of the code to var target = $("a[name='" + name.substring(1) + "']");
Note 2: In some cases, especially when you use the sticky bar from the bootstrap, the named a
will hide beneath the navigation bar. In those cases (or any similar case), you can reduce the number of the pixels from your scroll to achieve the optimal location. For example: $('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow');
will take you to the target
with 15 pixels left on the top.
I stumbled upon this example on https://css-tricks.com/snippets/jquery/smooth-scrolling/ explaining every line of code. I found this to be the best option.
https://css-tricks.com/snippets/jquery/smooth-scrolling/
You can go native:
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
window.scrollBy({
top: 100, // could be negative value
left: 0,
behavior: 'smooth'
});
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});
or with jquery:
$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {
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) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
}
}
});
$(function() {
$('a#top').click(function() {
$('html,body').animate({'scrollTop' : 0},1000);
});
});
Test it here:
following solution worked for me:
$("a[href^=#]").click(function(e)
{
e.preventDefault();
var aid = $(this).attr('href');
console.log(aid);
aid = aid.replace("#", "");
var aTag = $("a[name='"+ aid +"']");
if(aTag == null || aTag.offset() == null)
aTag = $("a[id='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top}, 1000);
}
);
'IT' 카테고리의 다른 글
Spring RestTemplate 요청에 "Accept :"헤더를 설정하는 방법은 무엇입니까? (0) | 2020.05.27 |
---|---|
요소를 전환하는 기본 jQuery 함수가 있습니까? (0) | 2020.05.27 |
현재 페이지에서 자바 스크립트를 사용하여 호스트 URL을 얻는 방법 (0) | 2020.05.27 |
Django의 ORM을 사용하여 무작위 레코드를 가져 오는 방법은 무엇입니까? (0) | 2020.05.27 |
Ruby에서 문자열의 Nil 또는 Length == 0을 확인하는 더 좋은 방법이 있습니까? (0) | 2020.05.27 |