如何将此Jquery代码转换为angularJs指令:
var lastScrollTop = 0;
$("div").scroll(function (event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
$('img').animate({top: '-=10'}, 10);
} else {
$('img').animate({top: '+=10'}, 10);
}
lastScrollTop = st;
});
答案 0 :(得分:1)
你不应该在这里使用selector,因为link函数提供了编译的DOM角度DOM。您可以像在代码中一样使用该DOM。 的标记强>
<div scroll-div>
Content here
</div>
<强>指令强>
app.directive('scrollDiv', function () {
return {
link: function (scope, element, attrs) {
var lastScrollTop = 0;
element.scroll(function (event) {
var st = element.scrollTop();
if (st > lastScrollTop) {
$('img').animate({
top: '-=10'
}, 10);
} else {
$('img').animate({
top: '+=10'
}, 10);
}
lastScrollTop = st;
});
}
});
答案 1 :(得分:0)
不知道你的标记是什么样的,你的应用程序被调用了什么,或者除此之外的任何东西都应该有效:
angular.module('myApp')
.directive('myScroll',
['$window', 'jQuery',
function($window, $) {
return {
restrict: 'A',
link: function ($scope, elem, attrs) {
$(elem).scroll(function (event) {
var st = $(this).scrollTop();
if (st > $scope.lastScrollTop) {
$('img').animate({top: '-=10'}, 10);
} else {
$('img').animate({top: '+=10'}, 10);
}
$scope.lastScrollTop = st;
});
}
};
}]);
示例标记:
<div myScroll>This is just some stupid text unworthy of being read, so please don't waste
<br>your time reading this nonesense.
<br>Hey! why are you still reading this garbage?
<br>Stop reading now and start doing something useful, such as getting this leaf to move up
<br>while you scroll this page.
<br>On second thought, maybe just continue reading.
<br>This might be more productive then whatever
<br>it is you were doing before.</div>
注意:restrict: 'A'
将指令限制为元素上的属性。
有关详细信息,请参阅Angular Directive Docs