Pushpin 是我们的固定定位插件。使用它可以在特定滚动范围内将元素固定到页面上。您可以查看我们的实际示例:右侧的固定目录。
打开演示演示代码
  $('.pushpin-demo-nav').each(function() {
    var $this = $(this);
    var $target = $('#' + $(this).attr('data-target'));
    $this.pushpin({
      top: $target.offset().top,
      bottom: $target.offset().top + $target.outerHeight() - $this.height()
    });
  });
        
  // Only necessary for window height sized blocks.
  html, body {
    height: 100%;
  }
        初始化
以下是 pushpin 的示例初始化。了解选项是什么,并根据需要对其进行自定义。
  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.pushpin');
    var instances = M.Pushpin.init(elems, options);
  });
  // Or with jQuery
  $(document).ready(function(){
    $('.pushpin').pushpin();
  });
        选项
| 名称 | 类型 | 默认值 | 描述 | 
|---|---|---|---|
| top | 数字 | 0 | 元素变为固定时距离页面顶部的像素距离。 | 
| bottom | 数字 | 无穷大 | 元素停止固定的距离页面顶部的像素距离。 | 
| offset | 数字 | 0 | 元素将被固定在顶部的偏移量。 | 
| onPositionChange | 函数 | null | pushpin 位置更改时调用的回调函数。为您提供一个位置字符串。 | 
方法
由于 jQuery 不再是依赖项,因此所有方法都在插件实例上调用。您可以这样获取插件实例
var instance = M.Pushpin.getInstance(elem); /* jQuery Method Calls You can still use the old jQuery plugin method calls. But you won't be able to access instance properties. $('.target').pushpin('methodName'); $('.target').pushpin('methodName', paramName); */
.destroy();
销毁插件实例并拆除
instance.destroy();
      属性
| 名称 | 类型 | 描述 | 
|---|---|---|
| el | 元素 | 用于初始化插件的 DOM 元素。 | 
| options | 对象 | 实例初始化时的选项。 | 
| originalOffset | 数字 | 元素的原始 offsetTop。 | 
CSS 类
固定元素有 3 种状态。一种在滚动阈值上方和下方,另一种是固定状态,元素在此状态下变为固定。由于固定会更改定位,因此当状态更改时,元素的外观可能会发生变化。使用这些 css 类正确设置 3 种状态的样式。
  // Class for when element is above threshold
  .pin-top {
    position: relative;
  }
  // Class for when element is below threshold
  .pin-bottom {
    position: relative;
  }
  // Class for when element is pinned
  .pinned {
    position: fixed !important;
  }
        