栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在AngularJS中处理锚点哈希链接

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在AngularJS中处理锚点哈希链接

您正在寻找

$anchorScroll()

这是(糟糕的)文档。

这是来源。

基本上,您只需将其注入并在控制器中调用它,它就会将您滚动到ID为的任何元素

$location.hash()

app.controller('TestCtrl', function($scope, $location, $anchorScroll) {   $scope.scrollTo = function(id) {      $location.hash(id);      $anchorScroll();   }});<a ng-click="scrollTo('foo')">Foo</a><div id="foo">Here you are</div>

这是一个演示的朋克

编辑:与路由一起使用

像往常一样设置角度布线,然后只需添加以下代码。

app.run(function($rootScope, $location, $anchorScroll, $routeParams) {  //when the route is changed scroll to the proper element.  $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {    $location.hash($routeParams.scrollTo);    $anchorScroll();    });});

并且您的链接如下所示:

<a href="#/test?scrollTo=foo">Test/Foo</a>

这是一个Plunker,展示了通过路由和$
anchorScroll进行滚动

甚至更简单:

app.run(function($rootScope, $location, $anchorScroll) {  //when the route is changed scroll to the proper element.  $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {    if($location.hash()) $anchorScroll();    });});

并且您的链接如下所示:

<a href="#/test#foo">Test/Foo</a>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633221.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号