亲爱的 friend /同事,
正如我在之前的一个问题中提到的,我刚开始学习 AngularJS,我有一个问题。
我想要完成的是以下内容:
我有一个大版本的 Logo 在 body 的 div 内,现在,我希望能够在导航栏中显示相同 Logo 的小版本,一旦大版本滚动出 View ,使用 AngularJS .我可以用 JQuery 和 scrollSpy 做到这一点,但该元素是特定于 AngularJS 的,而且我知道 Angular 可以处理这个任务,只是我似乎无法掌握它。
非常感谢任何帮助。
最佳答案
您可以为此编写和使用指令。其中,你应该使用滚动量,还有ng-show
在小标志上 div
指令返回的滚动量的最小值。
我会试着为你写指令
.directive('dirScrollTop', function($window, $parse) {
return {
scope: {
scroll: '=dirScrollTop'
},
link: function(scope, element, attrs) {
var windowEl = angular.element($window);
var handler = function(e) {
scope.scroll = $window.pageYOffset;
}
windowEl.on('scroll', scope.$apply.bind(scope, handler));
handler();
}
};
})
在html里面,把这个写在<div>
里面或 <img>
或...包含 Logo :
<div dir-scroll-top="scrollVariable" ng-show="scrollVariable > someValue">
在你的 Controller 中定义$scope.scrollVariable = 0
和 $scope.someValue
并为第二个提供滚动另一个所需的像素数量 <div>
看不见了……你应该给它分配一个像$scope.someValue=100;
这样的数字
我还应该说,最好使用 getBoundingClientRect()
动态地获得最高金额(特别是如果您的设计是响应式的并且距离不是静态的)在指令中像这样:
var someValue = element[0].getBoundingClientRect().top;
并检查指令内部的距离,并直接返回一个 bool 值。所以它会像这样:
var handler = function(e) {
var someValue = element[0].getBoundingClientRect().top;
var scrollOffset = $window.pageYOffset;
scope.scroll = $window.pageYOffset > someValue;
}
html 会是这样的:
<div dir-scroll-top="scrollVariable" ng-show="scrollVariable">
然后在 Controller 中定义:
$scope.scrollVariable = false;
更新:
所以如果我没记错的话,当窗口的滚动使较大的图像超出 View 时,您想显示/隐藏两个图像。
logoShow.directive('dirScrollTop', function($window, $parse) {
return {
scope: {
scroll: '=dirScrollTop'
},
link: function(scope, element, attrs) {
var windowEl = angular.element($window);
var someValue = element[0].getBoundingClientRect().bottom;
var handler = function(e) {
var scrollOffset = element[0].scrollTop;
scope.scroll = scrollOffset > someValue;
};
windowEl.on('scroll', scope.$apply.bind(scope, handler));
handler();
}
};
});
对于 html:
<div class="logo-big">
<img src="assets/img/logo_big.png" dir-scroll-top="scrollVariable" class="img-responsive center-block" />
</div>
和
<div class="navbar-brand" ng-show="scrollVariable">
<img src="assets/img/logo_menu.png" />
</div>
Controller :
logoShow.controller('logoShowCtrl', function($scope) {
$scope.scrollVariable = false;
});
这将在大图像完全超出 View 时显示 Logo (当它的底部到达 View 顶部时)。如果你想让它在大图的顶部到达 View 顶部时发生,你应该替换 element[0].getBoundingClientRect().bottom
与 element[0].getBoundingClientRect().top
在指令中。
关于javascript - 当 div 使用 AngularJS 滚动出 View 时在导航栏中显示 Logo ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35001002/