我有一个名为的自定义指令,当用户滚动列表时,标题必须显示在列表顶部,直到到达下一个。 问题是当我到达最后一个标题时它不会粘在顶部,也会滚动页面。
我的自定义指令
angular.module('myApp', [])
.directive('packageHeader', ['$window', function($window){
var stickies = [],
scroll = function scroll() {
angular.forEach(stickies, function($sticky, index) {
var sticky = $sticky[0],
pos = $sticky.data('pos');
if (pos <= $window.pageYOffset) {
var $next = stickies[index + 1],
next = $next ? $next[0] : null,
npos = $next.data('pos');
$sticky.addClass("fixed");
if (next && next.offsetTop >= npos - next.clientHeight)
$sticky.addClass("absolute").css("top", npos - sticky.clientHeight + 'px');
} else {
var $prev = stickies[index - 1],
prev = $prev ? $prev[0] : null;
$sticky.removeClass("fixed");
if (prev && $window.pageYOffset <= pos - prev.clientHeight)
$prev.removeClass("absolute").removeAttr("style");
}
});
},
//link function
link = function($scope, element, attrs) {
var sticky = element.children()[0],
$sticky = angular.element(sticky);
element.css('height', sticky.clientHeight + 'px');
$sticky.data('pos', sticky.offsetTop);
stickies.push($sticky);
};
angular.element($window).off('scroll', scroll).on('scroll', scroll);
return {
restrict: 'E',
transclude: true,
//sticky - getting from style sheet
template: '<sticky ng-transclude></sticky>',
link: link
};
}]);
HTML
<div class="demo">
<div>
<package-header>
<div>Header First</div>
</package-header>
<div class="whitespace">
Header First with content............. First Header
</div>
</div>
<div>
<package-header>
<div> Header Second </div>
</package-header>
<div class="whitespace">
Header second with content............. Second Header
</div>
这里我附上了我的代码https://plnkr.co/edit/VFyGlNk2641rg31nCq8O?p=preview
我希望最后一个标题也显示在顶部。 请帮我解决我的问题。