在AngularJS ScrollTo功能 [英] ScrollTo function in AngularJS
问题描述
我试图得到一个快速导航才能正常工作。它浮在一边。当他们点击一个链接,它需要他们的页面上的ID。我从以下树本指南。
这就是我对滚动:
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;
});
我最初把它放在&LT之前; /身体GT;
。但我似乎遇到了在那里被烧成快速导览编译之前的竞争条件(它有一个 NG-隐藏
置于其上,不知道如果这导致了它 - 但它是在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).
如果我运行code的该块在控制台,然后滚动按预期工作。
If I run that block of code in the console, then the scrolling works as expected.
我想这会更有效的这种移动到控制器 - 或指令中的可能性较大。但我没有运气实现这一。 我怎样才能获得code的此块与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");
});
}
}
});
演示:<一href=\"http://plnkr.co/edit/yz1EHB8ad3C59N6PzdCD?p=$p$pview\">http://plnkr.co/edit/yz1EHB8ad3C59N6PzdCD?p=$p$pview
有关帮助创建指令,检查出的视频在 http://egghead.io ,起始于10号第一次指令。
For help creating directives, check out the videos at http://egghead.io, starting at #10 "first directive".
修改:为了使滚动到一个指定的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");
});
}
}
});
然后,你可以使用它像这样:&LT; DIV滚动上点击&GT;&LT; / DIV&GT;
滚动到元素点击。或&LT;滚动上点击HREF =#元素ID&GT;&LT; / DIV&GT;
滚动到与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屋!