angular $anchorScroll操作滾動效果,類似錨點

先上主體代碼

 1. let old = $location.hash(); 
 2. $location.hash('right-sub-menu');  
 3. $anchorScroll();  
 4. $location.hash(old);

解釋:

$location.hash()

這個方法獲取當前錨點位置(即id),亦可設立錨點id。接收一個id值參數,如果要滾動到一個id=“aa”,就寫成

$location.hash("aa")

來看一個小解讀,本地項目地址爲

http://localhost:8080/nodejs-pro/angular/index.html 

第1句拿到當前錨點位置存在old裏,這裏是string ‘’,如可能indexhtml##menu,則拿到menu值

let old = $location.hash(); 

在這裏插入圖片描述
阮大俠:http://www.ruanyifeng.com/blog/2011/03/url_hash.html
第2句設定滾動位置

$location.hash('right-sub-menu');  //滾動到id爲right-sub-menu的元素位置 

第3句進行滾動

$anchorScroll();   //滾動! 

此時項目地址變成

http://localhost:8080/nodejs-pro/angular/index.html##right-sub-menu

第4句滾動到位後還原錨點(到之前的位置)

$location.hash(old); 

依賴的服務:

$location,$anchorScroll 

另外,在調用那個$anchorScroll()方法之前還可以設置相對於錨點位置的偏移量(從上到下抵消)

$anchorScroll.yOffset = 40;
or
$anchorScroll.yOffset = 500;
$anchorScroll();

再看效果。
比如錨點元素的垂直位置是600,如yoffset爲40則最終定位在560,如爲500最終定位在100.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章