首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 實現頁面錨點跳轉:滾動到指定元素或行數

     編輯:程式設計綜合問答

方法一:原生錨點

HTML 設置 id,URL 加 #id 或 JS 設置 location.hash = 'id'。

方法二:scrollIntoView(推薦)

const target = document.getElementById('section-3');
target.scrollIntoView({ behavior: 'smooth', block: 'start' });

方法三:計算座標滾動

const rect = target.getBoundingClientRect();
window.scrollTo({ top: rect.top + window.scrollY, behavior: 'smooth' });

行號跳轉

若需按行號跳轉,需預先建立行號與元素映射,或使用 document.getElementsByTagName('p')[lineNo] 定位。

總結

現代瀏覽器支援 scrollIntoView 平滑滾動,兼容性好,優先使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved