我正在使用 Angular Directive(指令)并将滚动绑定(bind)到窗口元素上。在滚动时,我想将元素移动到向上滚动的方向。然后,当 boundingRect
达到 50 时,我想应用固定定位。它不起作用...我错过了什么?
指令
app.directive('liftToTop', ['$window', function($window){
return {
restrict: 'A', //attributes only
link: function(scope, element, attrs) {
const w = angular.element($window),
topClass = attrs.liftToTop,
initialOffset = element.offset().top;
//bind the the scroll event
w.bind('scroll', function(){
console.log(this.pageYOffset);
let currentTop = element[0].getBoundingClientRect().top; //get current pos
if(currentTop > 50) {
//move element up/down against the scroll direction
element.css('top', -1 * this.pageYOffset + 'px');
element.removeClass(topClass);
}
//once current rect reaches 50, apply fixed
if(currentTop === 50) {
element.addClass(topClass);
}
});
}
};
}]);
CSS
.then-fixed-to-top-10 {
position:fixed;
top: 50px;
}
标记
<h1 lift-to-top="then-fixed-to-top-10">{{hello}}</h1>
这是无法正常工作的 Plnkr
最佳答案
如果我没理解错的话,主要问题是您测量滚动值的方式。此外,最后一个 if 语句必须从 ===
更改为 >
:
let currentTop = $(window).scrollTop(); //get current pos
if(currentTop < 50) {
//move element up/down against the scroll direction
element.css('top', -1 * this.pageYOffset + 'px');
element.removeClass(topClass);
}
//once current rect reaches 50, apply fixed
if(currentTop > 50) {
element.addClass(topClass);
}
要使 h1
保持不变而不向左跳,只需将 width:100%
添加到类中即可:
.then-fixed-to-top-10 {
position: fixed;
top: 50px;
width: 100%;
}
关于javascript - 在指令中将元素向上移动到窗口滚动然后应用固定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41506948/