搜尋
首頁web前端js教程用JavaScript使內部鏈接順利滾動

Make Internal Links Scroll Smoothly with JavaScript

這種方法遵循不引人注目的DHTML的原則,使每個人都可以輕鬆使用。為了使解決方案工作,腳本需要由某些東西運行;我們將代碼從第一步(在鏈接上循環以找到內部的鏈接)將代碼放入函數ss_fixalllinks()中,並使用Scott Andrew的函數將其綁定到窗口的Onload事件中:

>
ss_addEvent(window,"load",ss_fixAllLinks);

整個代碼看起來像這樣:

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  window.scrollTo(0,wascypos + scramount);  
 iscypos = ss_getCurrentYPos();  
 isAboveNow = (iscypos  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);
總結
您的文檔內部鏈接將滾動到他們的目的地,使您的用戶能夠保持對瀏覽器在文檔中的位置以及距離起點有多遠的認識。該代碼已經過測試並在Mozilla,即IE和Opera工作;它在Konqueror不起作用,並且假定在其他瀏覽器中不起作用。

>

>常見問題(常見問題解答)關於使用JavaScript平滑滾動的問題

>如何在JavaScript中實現光滑的滾動?此方法採用兩個參數:窗口應滾動的X坐標和Y坐標。為了使滾動光滑,您可以使用行為屬性並將其設置為“光滑”。這是一個簡單的示例:

窗口。在頁面上。您可以通過首先使用諸如document.queryselector之類的方法選擇元素,然後在所選元素上使用scrollintoview方法來完成此操作。以下是一個示例:

var element = document.queryselector('#myElement');
emelt.scrollintoview({crathion:'smooth'smooth'});
>此代碼將平滑地滾動窗口,並使用id“ myElement”。 JavaScript得到了大多數現代瀏覽器的支持,包括Chrome,Firefox,Safari和Edge。但是,Internet Explorer不支持它。您可以查看MDN Web文檔上的兼容性表以獲取最新信息。

我可以控制光滑滾動的速度嗎?
>平滑滾動的速度由瀏覽器確定,並且不能用JavaScript直接控制。但是,您可以使用window.requestanimationframe方法來創建一個自定義的平滑滾動函數。

>如何通過javaScript實現平滑滾動以進行錨鏈接?

您可以通過在鏈接上添加“單擊”事件的事件偵聽器來實現錨鏈接的平滑滾動。如果事件處理程序,您可以防止鏈接的默認操作,即立即導航到目標元素,而是使用scrollintoview方法平滑滾動到目標元素。以下是一個示例:

document.queryselectorall('a [href^=“#”]')。 document.queryselector(this.getAttribute('href'))。 scrollIntoview({{
行為:'smooth'
});
});
});
});
>
此代碼將在頁面上添加平穩的scroll scrolls。
是的,使用JavaScript平滑滾動時,您可以添加滾動偏移量。您可以通過從scollto方法中的y坐標或scrollintoview方法中的y坐標中減去所需的偏移來做到這一點。

我可以使用jQuery實現平滑的滾動滾動嗎? jQuery提供了動畫方法,您可以使用該方法將HTML和身體元素的Scrolltop屬性進行動畫。 Here’s an example:

$('html, body').animate({

scrollTop: $("#myElement").offset().top

}, 2000);

This code will smoothly scroll the window to the element with the id ‘myElement’ over a period of 2 seconds.

Can I implement smooth scrolling with CSS instead JavaScript?

是的,您可以使用滾動行為屬性通過CSS實現平滑的滾動。您可以將此屬性設置為在HTML或身體元素上“平滑”,以使整個頁面平滑滾動。但是,此方法比JavaScript方法具有較少的瀏覽器支持。

如何測試光滑的滾動是否正常工作?
>您可以通過簡單地嘗試在頁面上滾動來測試平滑滾動是否正常工作。如果滾動光滑而不是瞬間,則可以正常工作。您還可以使用瀏覽器中的開發人員工具來檢查滾動行為。

我可以使用JavaScript使用JavaScript的光滑滾動嗎?

​​

是的,您可以通過不使用scrollto或ScrollIntoview方法或設置它來設置'auto'來通過JavaScript禁用JavaScript的光滑滾動。這將使滾動瞬間而不是光滑。

以上是用JavaScript使內部鏈接順利滾動的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
node.js流帶打字稿node.js流帶打字稿Apr 30, 2025 am 08:22 AM

Node.js擅長於高效I/O,這在很大程度上要歸功於流。 流媒體匯總處理數據,避免內存過載 - 大型文件,網絡任務和實時應用程序的理想。將流與打字稿的類型安全結合起來創建POWE

Python vs. JavaScript:性能和效率注意事項Python vs. JavaScript:性能和效率注意事項Apr 30, 2025 am 12:08 AM

Python和JavaScript在性能和效率方面的差異主要體現在:1)Python作為解釋型語言,運行速度較慢,但開發效率高,適合快速原型開發;2)JavaScript在瀏覽器中受限於單線程,但在Node.js中可利用多線程和異步I/O提升性能,兩者在實際項目中各有優勢。

JavaScript的起源:探索其實施語言JavaScript的起源:探索其實施語言Apr 29, 2025 am 12:51 AM

JavaScript起源於1995年,由布蘭登·艾克創造,實現語言為C語言。 1.C語言為JavaScript提供了高性能和系統級編程能力。 2.JavaScript的內存管理和性能優化依賴於C語言。 3.C語言的跨平台特性幫助JavaScript在不同操作系統上高效運行。

幕後:什麼語言能力JavaScript?幕後:什麼語言能力JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript在瀏覽器和Node.js環境中運行,依賴JavaScript引擎解析和執行代碼。 1)解析階段生成抽象語法樹(AST);2)編譯階段將AST轉換為字節碼或機器碼;3)執行階段執行編譯後的代碼。

Python和JavaScript的未來:趨勢和預測Python和JavaScript的未來:趨勢和預測Apr 27, 2025 am 12:21 AM

Python和JavaScript的未來趨勢包括:1.Python將鞏固在科學計算和AI領域的地位,2.JavaScript將推動Web技術發展,3.跨平台開發將成為熱門,4.性能優化將是重點。兩者都將繼續在各自領域擴展應用場景,並在性能上有更多突破。

Python vs. JavaScript:開發環境和工具Python vs. JavaScript:開發環境和工具Apr 26, 2025 am 12:09 AM

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

JavaScript是用C編寫的嗎?檢查證據JavaScript是用C編寫的嗎?檢查證據Apr 25, 2025 am 12:15 AM

是的,JavaScript的引擎核心是用C語言編寫的。 1)C語言提供了高效性能和底層控制,適合JavaScript引擎的開發。 2)以V8引擎為例,其核心用C 編寫,結合了C的效率和麵向對象特性。 3)JavaScript引擎的工作原理包括解析、編譯和執行,C語言在這些過程中發揮關鍵作用。

JavaScript的角色:使網絡交互和動態JavaScript的角色:使網絡交互和動態Apr 24, 2025 am 12:12 AM

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具