我使用angular指令并绑定窗口元素上的滚动。在滚动时,我想要将元素移向向上滚动的方向。然后,当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
答案 0 :(得分:0)
如果我理解正确,主要问题是你测量滚动值的方式。此外,最后一个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%;
}
:
add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');
function myStartSession() {
if(!session_id()) {
session_start();
}
}
function myEndSession() {
session_destroy ();
}
答案 1 :(得分:0)
我需要将初始偏移量除以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;
}