[英]Sidebar to scroll down/up as user scroll down/up the browser window without using position: sticky and fixed?
[英]Move element up against window scroll in a directive then apply fixed position
我正在使用angular指令并将滚动条绑定到window元素上。 在滚动时,我想将元素逆着向上滚动的方向移动。 然后,当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
棍子不跳到左侧,只需将class的width:100%
添加:
.then-fixed-to-top-10 {
position: fixed;
top: 50px;
width: 100%;
}
我需要将初始偏移量除以2才能达到一半。 我还需要将移动div的宽度设置为等于父div的宽度,以防止跳跃。
指示
app.directive('liftToTop', function($window){
return {
restrict: 'A',
link: function(scope, element, attrs){
const w = angular.element($window),
topClass = attrs.liftToTop,
initialOffset = element.offset().top;
w.bind('scroll', function(){
let currentTop = w.scrollTop(); //get current pos
if(currentTop < initialOffset / 2) {
//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 > (initialOffset / 2)) {
element.addClass(topClass);
element.removeAttr('style');
}
});
}
};
});
CSS
.fixed-to-top-10 {
position:fixed;
top: 0px;
width: 400px;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.