> 웹 프론트엔드 > JS 튜토리얼 > 내부 링크를 JavaScript로 부드럽게 스크롤하게 만듭니다

내부 링크를 JavaScript로 부드럽게 스크롤하게 만듭니다

尊渡假赌尊渡假赌尊渡假赌
풀어 주다: 2025-03-08 00:43:10
원래의
722명이 탐색했습니다.

이 접근법은 눈에 띄지 않는 DHTML의 원칙을 따르므로 모든 사람이 쉽게 사용할 수 있습니다. 해결책이 작동하려면 스크립트를 무언가에 의해 실행해야합니다. 우리는 첫 번째 단계에서 코드를 (내부에있는 링크를 통해 루핑) 함수 ss_fixalllinks ()에 넣고 Scott Andrew의 기능을 사용하여 Window의 Onload 이벤트에 바인딩합니다. Make Internal Links Scroll Smoothly with JavaScript 전체 코드는 다음과 같습니다 포장

문서 내부 링크가 대상으로 스크롤하여 사용자는 브라우저가 문서 내의 위치와 시작점에서 얼마나 멀리 있는지에 대한 인식을 유지할 수 있습니다. 코드는 테스트되었으며 Mozilla, IE 및 Opera에서 작동합니다. Konqueror에서는 작동하지 않으며 다른 브라우저에서는 작동하지 않는 것으로 가정합니다. JavaScript로 스무딩 스크롤에 대한 자주 묻는 질문 (FAQ) JavaScript에서 매끄러운 스크롤을 구현하려면

JavaScript에서 부드러운 스크롤을 구현하려면 Window.scrollto 메소드를 사용하는 것과 관련이 있습니다. 이 방법은 두 가지 인수를 취합니다. X 좌표와 창이 스크롤 해야하는 y 코디네이션. 스크롤을 매끄럽게 만들려면 동작 속성을 사용하여 '매끄러운'상태로 설정할 수 있습니다. 간단한 예는 다음과 같습니다.
ss_addEvent(window,"load",ss_fixAllLinks);
로그인 후 복사
wink 페이지에. Document.querySelector와 같은 메소드를 사용하여 요소를 먼저 선택한 다음 선택한 요소에서 ScrollIntoView 메소드를 사용 하여이 작업을 수행 할 수 있습니다. 예는 다음과 같습니다.

var element = document.querySelector ( '##myElement'); element.scrollIntoview ({behavior : 'smald'}); 이 코드는 ID 'myElement'로 요소로 창을 매끄럽게 스크롤 할 것입니다. JavaScript는 Chrome, Firefox, Safari 및 Edge를 포함한 대부분의 최신 브라우저에서 지원됩니다. 그러나 Internet Explorer는 지원하지 않습니다. MDN 웹 문서에서 가장 최신 정보에 대해 호환성 테이블을 확인할 수 있습니다.

부드러운 스크롤의 속도를 제어 할 수 있습니까?
function ss_fixAllLinks() {   
 // Get a list of all links in the page  
 var allLinks = document.getElementsByTagName('a');  
 // Walk through the list  
 for (var i=0;i    var lnk = allLinks[i];  
   if ((lnk.href && lnk.href.indexOf('#') != -1) &&    
       ( (lnk.pathname == location.pathname) ||  
   ('/'+lnk.pathname == location.pathname) ) &&    
       (lnk.search == location.search)) {  
     // If the link is internal to the page (begins in #)  
     // then attach the smoothScroll function as an onclick  
     // event handler  
     ss_addEvent(lnk,'click',smoothScroll);  
   }  
 }  
}  
 
function smoothScroll(e) {  
 // This is an event handler; get the clicked on element,  
 // in a cross-browser fashion  
 if (window.event) {  
   target = window.event.srcElement;  
 } else if (e) {  
   target = e.target;  
 } else return;  
   
 // Make sure that the target is an element, not a text node  
 // within an element  
 if (target.nodeType == 3) {  
   target = target.parentNode;  
 }  
   
 // Paranoia; check this is an A tag  
 if (target.nodeName.toLowerCase() != 'a') return;  
   
 // Find the tag corresponding to this href  
 // First strip off the hash (first character)  
 anchor = target.hash.substr(1);  
 // Now loop all A tags until we find one with that name  
 var allLinks = document.getElementsByTagName('a');  
 var destinationLink = null;  
 for (var i=0;i    var lnk = allLinks[i];  
   if (lnk.name && (lnk.name == anchor)) {  
     destinationLink = lnk;  
     break;  
   }  
 }  
   
 // If we didn't find a destination, give up and let the browser do  
 // its thing  
 if (!destinationLink) return true;  
   
 // Find the destination's position  
 var destx = destinationLink.offsetLeft;    
 var desty = destinationLink.offsetTop;  
 var thisNode = destinationLink;  
 while (thisNode.offsetParent &&    
       (thisNode.offsetParent != document.body)) {  
   thisNode = thisNode.offsetParent;  
   destx += thisNode.offsetLeft;  
   desty += thisNode.offsetTop;  
 }  
   
 // Stop any current scrolling  
 clearInterval(ss_INTERVAL);  
   
 cypos = ss_getCurrentYPos();  
   
 ss_stepsize = parseInt((desty-cypos)/ss_STEPS);  
 ss_INTERVAL = setInterval('ss_scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);  
   
 // And stop the actual click happening  
 if (window.event) {  
   window.event.cancelBubble = true;  
   window.event.returnValue = false;  
 }  
 if (e && e.preventDefault && e.stopPropagation) {  
   e.preventDefault();  
   e.stopPropagation();  
 }  
}  
 
function ss_scrollWindow(scramount,dest,anchor) {  
 wascypos = ss_getCurrentYPos();  
 isAbove = (wascypos < dest);  
 window.scrollTo(0,wascypos + scramount);  
 iscypos = ss_getCurrentYPos();  
 isAboveNow = (iscypos < dest);  
 if ((isAbove != isAboveNow) || (wascypos == iscypos)) {  
   // if we've just scrolled past the destination, or  
   // we haven't moved from the last scroll (i.e., we're at the  
   // bottom of the page) then scroll exactly to the link  
   window.scrollTo(0,dest);  
   // cancel the repeating timer  
   clearInterval(ss_INTERVAL);  
   // and jump to the link directly so the URL's right  
   location.hash = anchor;  
 }  
}  
 
function ss_getCurrentYPos() {  
 if (document.body && document.body.scrollTop)  
   return document.body.scrollTop;  
 if (document.documentElement && document.documentElement.scrollTop)  
   return document.documentElement.scrollTop;  
 if (window.pageYOffset)  
   return window.pageYOffset;  
 return 0;  
}  
 
function ss_addEvent(elm, evType, fn, useCapture)  
// addEvent and removeEvent  
// cross-browser event handling for IE5+,  NS6 and Mozilla  
// By Scott Andrew  
{  
 if (elm.addEventListener){  
   elm.addEventListener(evType, fn, useCapture);  
   return true;  
 } else if (elm.attachEvent){  
   var r = elm.attachEvent("on"+evType, fn);  
   return r;  
 }  
}    
 
var ss_INTERVAL;  
var ss_STEPS = 25;  
 
ss_addEvent(window,"load",ss_fixAllLinks);
스무딩 스크롤의 속도는 브라우저에서 결정되며 JavaScript로 직접 제어 할 수 없습니다. 그러나 Window.RequestAnimationFrame 메소드를 사용하여 설정 속도로 사용자 정의 스무딩 스크롤 기능을 만들 수 있습니다. 앵커 링크에 대한 JavaScript로 매끄러운 스크롤을 구현하려면 링크에서 '클릭'이벤트에 대한 이벤트 리스너를 추가하여 앵커 링크에 대한 부드러운 스크롤을 구현할 수 있습니다. 이벤트 핸들러에서는 대상 요소로 즉시 탐색하는 링크의 기본 동작을 방지하고 ScrollIntoview 메소드를 사용하여 대상 요소로 부드럽게 스크롤합니다. 예는 다음과 같습니다.

document.querySelectorall ( 'a [href^= "#"]'). foreach (앵커 => { anchor.addeventListener ( 'click', function (e) {

> document.querySelector (this.getAttribute ( 'href')). scrollintoview ({ 동작 : 'smooth'}); 이 코드는 모든 앵커 링크에 매끄러운 스크롤을 추가 할 것입니다. 예, JavaScript로 스무 스크롤을 사용할 때 스크롤 오프셋을 추가 할 수 있습니다. Scrollto Method의 y 좌표 또는 Scrollintoview 메소드의 상단 특성에서 원하는 오프셋을 빼면이를 수행 할 수 있습니다.
jQuery를 사용하여 부드러운 스크롤을 구현할 수 있습니까?

예, JQuery를 사용하여 매끄러운 스크롤을 구현할 수 있습니다. JQuery는 애니메이션 방법을 제공하며,이 방법은 HTML 및 바디 요소의 스크롤 탑 속성을 애니메이션하는 데 사용할 수 있습니다. 예는 다음과 같습니다.
$ ( 'html, body'). 애니메이션 ({ scrolltop : $ ( "#mylement"). htset (). top 이 코드는 2 초 동안 id 'myelement'로 요소를 부드럽게 스크롤합니다. JavaScript의?
예, 스크롤-행동 속성을 사용하여 CSS로 매끄러운 스크롤을 구현할 수 있습니다. 이 속성을 HTML 또는 바디 요소에서 '매끄럽게'설정하여 전체 페이지의 매끄러운 스크롤을 가능하게합니다. 그러나이 방법은 JavaScript 메소드보다 브라우저 지원이 적습니다.
스무딩 스크롤링이 올바르게 작동하는지 테스트 할 수있는 방법은 무엇입니까?
페이지에서 스크롤을 스크롤하려고 시도하여 매끄러운 스크롤링이 올바르게 작동하는지 테스트 할 수 있습니다. 스크롤이 매끄럽고 순간이 아닌 경우 올바르게 작동합니다. 브라우저의 개발자 도구를 사용하여 스크롤 동작을 검사 할 수도 있습니다.
JavaScript로 매끄러운 스크롤을 비활성화 할 수 있습니까?
예, 스크롤 또는 스크롤리 켜기 메소드에서 동작 속성을 사용하지 않거나 '자동'으로 설정하여 JavaScript를 비활성화 할 수 있습니다. 이것은 스크롤을 매끄럽지 않고 즉각적으로 만듭니다

위 내용은 내부 링크를 JavaScript로 부드럽게 스크롤하게 만듭니다의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿