javascript - 在指令中将元素向上移动到窗口滚动然后应用固定位置

标签 javascript jquery css angularjs angularjs-directive

我正在使用 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

https://plnkr.co/edit/n4dQDzwK5T6e3TqWGlR3?p=preview

最佳答案

如果我没理解错的话,主要问题是您测量滚动值的方式。此外,最后一个 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/

相关文章:

没有图像的CSS斑马条纹背景

javascript - &lt;script&gt; 标签内的 Vuejs 单文件组件 (.vue) 模型更新

javascript - 如何使 jquery 脚本更短?

css - 如何更改 Metro UI 中输入控件的大小?

javascript - 语法错误: illegal character &#39; Passing a 2D List to JavaScript

javascript - 将变量从 "pretty"URL 传递给 Javascript

html - 页面 anchor 链接导致整个内容 div 移动

javascript - 如何通过 JavaScript 使用简单的 REST API

javascript - 创建一个接口(interface),其键是枚举的值

javascript - JS $ 是什么意思?