AngularJS 中的 ScrollTo 函数 [英] ScrollTo function in AngularJS

查看:19
本文介绍了AngularJS 中的 ScrollTo 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试快速导航以正常工作.它漂浮在一边.当他们点击一个链接时,它会将他们带到页面上的那个 ID.我正在关注 来自 Treehouse 的指南.这是我滚动的内容:

I'm trying to get a quick nav to work correctly. It's floating on the side. When they click on a link, it takes them to that ID on the page. I'm following this guide from Treehouse. This is what I have for the scrolling:

$("#quickNav a").click(function(){
    var quickNavId = $(this).attr("href");
    $("html, body").animate({scrollTop: $(location).offset().top}, "slow");
    return false;
});

我最初将它放在 </body> 之前.但我似乎遇到了在 quickNav 编译之前触发的竞争条件(它有一个 ng-hide 放在上面,不确定是否是导致它 - 但它在 DOM 中).

I initially placed it before the </body>. But I seem to be running into a race condition where that was firing before the quickNav compiled (it has a ng-hide placed on it, not sure if that's causing it - but it is within the DOM).

如果我在控制台中运行该代码块,则滚动按预期工作.

If I run that block of code in the console, then the scrolling works as expected.

我认为将其移动到控制器中会更有效 - 或者更有可能在指令中.但我没有运气做到这一点.如何让这段代码与 AngularJS 一起工作?

I figured it'd be more effective to move this into the controller - or more likely within a directive. But I'm not having luck accomplishing that. How can I get this block of code to work with AngularJS?

推荐答案

这是一个简单的指令,它会在点击时滚动到一个元素:

Here is a simple directive that will scroll to an element on click:

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm) {
      $elm.on('click', function() {
        $("body").animate({scrollTop: $elm.offset().top}, "slow");
      });
    }
  }
});

演示:http://plnkr.co/edit/yz1EHB8ad3C59N6PzdCD?p=preview

有关创建指令的帮助,请查看 http://egghead.io 上的视频,从 #10first指令".

For help creating directives, check out the videos at http://egghead.io, starting at #10 "first directive".

edit:要使其滚动到由 href 指定的特定元素,只需检查 attrs.href.

edit: To make it scroll to a specific element specified by a href, just check attrs.href.

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm, attrs) {
      var idToScroll = attrs.href;
      $elm.on('click', function() {
        var $target;
        if (idToScroll) {
          $target = $(idToScroll);
        } else {
          $target = $elm;
        }
        $("body").animate({scrollTop: $target.offset().top}, "slow");
      });
    }
  }
});

然后你可以这样使用它:<div scroll-on-click></div> 滚动到点击的元素.或者 <a scroll-on-click href="#element-id"></div> 滚动到带有 id 的元素.

Then you could use it like this: <div scroll-on-click></div> to scroll to the element clicked. Or <a scroll-on-click href="#element-id"></div> to scroll to element with the id.

这篇关于AngularJS 中的 ScrollTo 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆