[英]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.