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.

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