React Js 實現錨點定位的集中方法

React Js 實現錨點定位的集中方法

注:以水平錨點定位爲例,垂直方向亦如此html

方法1. url hash值跳轉

到達頁面可視位置,滾動區域的左/右邊,無滾動的平滑效果,效果差。api

設置,用戶點擊並跳轉
<a href="#anchorId">錨點1</a>
待跳轉標識的位置,使用id
<div id="anchorId">錨點1</div>
或使用a標籤,name屬性
<a name="anchorId"></a>
可代碼控制錨點跳轉
window.location.hash = anchorId;
補充知識點 http://www.ruanyifeng.com/blog/2011/03/url_hash.html

hash,url中的錨點信息部分。以#開始後面內容,表明網頁中的一個位置,改變#後的部分,瀏覽器只會滾動到相應位置,不會從新加載網頁,但會改變瀏覽器的訪問歷史(非IE)瀏覽器

方法2. scrollToAnchor

內容定位到滾動容器可視區域,滾動區域正中間,較難控制定位位置,有滾動滑動效果,h5新增api,存在瀏覽器兼容性,效果通常。函數

待跳轉標識的位置
<a id="screens"></a>
定位函數
scrollToAnchor = (anchorId) => {
    if (anchorId) {   // 找到錨點 id
        let anchorElement = document.getElementById(anchorId);
        if(anchorElement) {        // 若是對應id的錨點存在,就跳轉到錨點
			anchorElement.scrollIntoView({block: 'start', behavior: 'smooth'});
		}
    }
}
補充知識點 https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

scrollIntoView h5新增api,存在瀏覽器兼容性;取決於其它元素的佈局狀況,此元素可能不會徹底滾動到頂端或底端佈局

方法3. 滾動容器的scrollLeft設置爲須要定位元素的offsetLeft

內容定位到滾動容器可視區域,位置定位到靠左(靠右,可自行計算),無滾動滑動效果。實現簡單,效果呆板。url

let scrollElement = document.getElementById(scrollId);    // 對應id的滾動容器
let anchorElement = document.getElementById(anchorId);  // 須要定位看到的錨點元素
if(scrollElement) {
	scrollElement.scrollLeft = anchorElement.offsetLeft;
}
補充知識點 https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollLeft

scrollLeft 表明元素滾動條距離元素左邊多少像素code

方法4. 滾動容器 scrollTo()

內容定位到滾動容器可視區域,位置定位到靠左,有滾動滑動效果,效果好。htm

let scrollElement = document.getElementById(scrollId);    // 對應id的滾動容器
let anchorElement = document.getElementById(anchorId);  // 須要定位看到的錨點元素
if(scrollElement) {
	scrollElement.scrollTo({left: anchorElement.offsetLeft, behavior: "smooth" });
}
補充知識點 https://developer.mozilla.org/zh-CN/docs/Web/API/Window/scrollTo
相關文章
相關標籤/搜索