71

Instagram 应用程序有一个很好的粘性标题,可以将当前的标题推到新的位置。我找到了一个很棒的教程,关于如何在 Android 上原生地做到这一点,但我希望用 JavaScript 和 CSS 来做到这一点。

我能够让我的标题换一个新的,但我似乎无法找到一种方法来模仿 Instagram 的做法。任何帮助是极大的赞赏。

*编辑:在评论中使用航点作为 Cj 滚动时,我能够让页眉贴在页面顶部。(链接到航点)。我遇到的主要问题是 instagram 在他们的 iPhone 移动应用程序中使用的“上推”效果。我会链接到一个例子,但我以前从未见过它使用过。*

* *编辑 2:使用@Chris 提供的部分代码笔,我能够让标题保持不变。然后我添加了一个 .slideUp 效果。我现在的问题是让 .slideUp 效果仅在到达下一个标题时发生。现在效果在滚动时激活。

这是代码:

(function() {
function stickyTitles(stickies) {
    this.load = function() {
        stickies.each(function(){
            var thisSticky = jQuery(this);
            jQuery.data(thisSticky[0], 'pos', thisSticky.offset().top);
        });
    }
    this.scroll = function() {      
        stickies.each(function(){           
            var thisSticky = jQuery(this),          
                pos = jQuery.data(thisSticky[0], 'pos');
            if (pos <= jQuery(window).scrollTop()) {
                thisSticky.addClass("fixed");
                // added this 
                 $(".followMeBar:parent").slideUp();

            } else {
                thisSticky.removeClass("fixed");
            }
        });         
    }
}
jQuery(document).ready(function(){
    var newStickies = new stickyTitles(jQuery(".followMeBar"));
    newStickies.load();
    jQuery(window).on("scroll", function() {
        newStickies.scroll();

    }); 
});

})();

4

8 回答 8

133

对此没有快速或简单的答案,但通过一些创造性的哄骗,我们可以模拟相同的功能。

我们需要的是一系列我们可以识别、循环然后设置的元素,以便当我们点击它们在页面上的位置时,前一个项目被向上推,新项目变得固定。我们将需要使用 jQuery 的offset().top方法检索元素的初始位置并将其存储在data标签中,以便我们以后可以引用它。然后其余的将在我们滚动时计算。

这应该可以解决问题:

var stickyHeaders = (function() {

  var $window = $(window),
      $stickies;

  var load = function(stickies) {

    if (typeof stickies === "object" && stickies instanceof jQuery && stickies.length > 0) {

      $stickies = stickies.each(function() {

        var $thisSticky = $(this).wrap('<div class="followWrap" />');
  
        $thisSticky
            .data('originalPosition', $thisSticky.offset().top)
            .data('originalHeight', $thisSticky.outerHeight())
              .parent()
              .height($thisSticky.outerHeight()); 			  
      });

      $window.off("scroll.stickies").on("scroll.stickies", function() {
		  _whenScrolling();		
      });
    }
  };

  var _whenScrolling = function() {

    $stickies.each(function(i) {			

      var $thisSticky = $(this),
          $stickyPosition = $thisSticky.data('originalPosition');

      if ($stickyPosition <= $window.scrollTop()) {        
        
        var $nextSticky = $stickies.eq(i + 1),
            $nextStickyPosition = $nextSticky.data('originalPosition') - $thisSticky.data('originalHeight');

        $thisSticky.addClass("fixed");

        if ($nextSticky.length > 0 && $thisSticky.offset().top >= $nextStickyPosition) {

          $thisSticky.addClass("absolute").css("top", $nextStickyPosition);
        }

      } else {
        
        var $prevSticky = $stickies.eq(i - 1);

        $thisSticky.removeClass("fixed");

        if ($prevSticky.length > 0 && $window.scrollTop() <= $thisSticky.data('originalPosition') - $thisSticky.data('originalHeight')) {

          $prevSticky.removeClass("absolute").removeAttr("style");
        }
      }
    });
  };

  return {
    load: load
  };
})();

$(function() {
  stickyHeaders.load($(".followMeBar"));
});
.followMeBar {
  background: #999;
  padding: 10px 20px;
  position: relative;
  z-index: 1;
  color: #fff;
}
.followMeBar.fixed {
  position: fixed;
  top: 0;
  width: 100%;
  box-sizing: border-box;
  z-index: 0;
}
.followMeBar.fixed.absolute {
  position: absolute;
}
/* For aesthetics only */

body {
  margin: 0;
  font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="followMeBar">A</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">B</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">C</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">D</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">E</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">F</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">G</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">H</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">I</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">J</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">K</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">L</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">M</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">N</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">O</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">P</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">Q</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">R</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">S</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">T</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">U</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">V</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">W</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">X</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">Y</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="followMeBar">Z</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

这是纯 CSS 版本:

在你说“什么?!当只有 CSS 版本时,我刚刚经历了所有这些?!”之前 它只适用于几个浏览器。例如在 Firefox 中试试这个:

.sticky {
  position: -webkit-sticky;
  position: -moz-sticky;
  position: -o-sticky;
  position: -ms-sticky;
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  display: block;
  z-index: 1;
  background: #999;
  color: #fff;
  padding: 10px 20px;
}

/* For aesthetics only */
body {
  margin: 0;
  font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif;
}
<div data-lorem="p">
  <span class="sticky">a</span>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</div>
<div data-lorem="p">
  <span class="sticky">b</span>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</div>
<div data-lorem="p">
  <span class="sticky">c</span>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</div>
<div data-lorem="p">
  <span class="sticky">d</span>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</div>
<div data-lorem="p">
  <span class="sticky">e</span>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</div>
<div data-lorem="p">
  <span class="sticky">f</span>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</div>
<div data-lorem="p">
  <span class="sticky">g</span>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</div>
<div data-lorem="p">
  <span class="sticky">h</span>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</div>

http://caniuse.com/#feat=css-sticky

于 2012-11-08T16:49:29.167 回答
6

首先,感谢@Chris Spittles 的出色回答。

我创建了一个修改版本,无需包装每个粘性元素,因为它只是更改它们的相对位置而不是使用固定定位。

var stickyHeaders = (function() {

    var $stickies;

    var load = function(stickies, target) {

        if (typeof stickies === "object" && stickies instanceof jQuery && stickies.length > 0) {

            $stickies = stickies.each(function() {

                var $thisSticky = $(this);

                $thisSticky
                    .data('originalPosition', $thisSticky.offset().top)
                    .data('originalHeight', $thisSticky.outerHeight());               
            });

            target.off("scroll.stickies").on("scroll.stickies", function(event) {
                 _whenScrolling(event);     
            });
        }
    };

    var _whenScrolling = function(event) {

        var $scrollTop = $(event.currentTarget).scrollTop();

        $stickies.each(function(i) {            

            var $thisSticky = $(this),
                $stickyPosition = $thisSticky.data('originalPosition'),
                $newPosition,
                $nextSticky;

            if ($stickyPosition <= $scrollTop) {

                $newPosition = Math.max(0, $scrollTop - $stickyPosition);
                $nextSticky = $stickies.eq(i + 1);

                if($nextSticky.length > 0) {

                    $newPosition = Math.min($newPosition, ($nextSticky.data('originalPosition') -  $stickyPosition) - $thisSticky.data('originalHeight'));
                }

            } else {

                $newPosition = 0;
            }

            $thisSticky.css('transform', 'translateY(' + $newPosition + 'px)');

            //could just as easily use top instead of transform
            //$thisSticky.css('top', $newPosition + 'px');
        });
    };

    return {
        load: load
    };
})();

$(function() {
    stickyHeaders.load($(".followMeBar"), $(window));
});

css被简化为:

.followMeBar {
    background: #999;
    padding: 10px 20px;
    position: relative;
    z-index: 1;
    color: #fff;
}

/* For aesthetics only */

body {
    margin: 0;
    font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif;
}

http://plnkr.co/edit/wk3h40LfBdN1UFtDLZgY?p=preview

这是另一个示例,展示了在使用固定标头时如何使用偏移量:

http://plnkr.co/edit/8YBqdCIKruVKYRXbZnCp?p=preview

于 2015-08-16T14:44:51.873 回答
3

我尝试了上面提供的解决方案,但没有一个可以完美运行而没有错误(主要是滚动和浏览器兼容性的错误)。刚刚找到了这个https://github.com/sarahdayan/feedify,它对我很有用。

于 2015-10-18T06:13:46.460 回答
2

确保将其包裹在div

注意第 6 个标题,因为它没有被包裹div

h1, h2{
position: sticky;
top: 0;
}

div{
height: 500px;
}
<div>
<h1>lorem ipsum doloro sit <br> amet 1</h1>
</div>

<div>
<h1>lorem ipsum doloro sit 2</h1>
</div>

<div>
<h2>lorem ipsum doloro sit 3</h2>
</div>

<div>
<h1>lorem ipsum doloro sit <br> amet 4</h1>
</div>

<div>
<h2>lorem ipsum doloro sit <br> amet 5</h2>
</div>

<h2>lorem ipsum doloro sit <br> amet 6</h2>

<div></div>

<div>
<h1>lorem ipsum doloro sit  7</h1>
</div>

<div>
<h1>lorem ipsum doloro sit <br> amet 8</h1>
</div>

<div>
<h1>lorem ipsum doloro sit <br> amet 9</h1>
</div>

于 2020-05-24T18:40:57.880 回答
1

我很难让克里斯的答案为我准确地工作,因为所有的便利贴都在一个相对定位的 div 内(上面有一个标题,在相对 div 之外) - 这个答案只是存储 .offset() var 中相对容器 div 的 .top 并从脚本中的 .css('top', value ) 中减去它。就像在 chris 的版​​本中一样,最高价值是推开文档的顶部,这可以正常工作。当您添加相对 div 时,top 现在是从顶部推动,因此相对 div 上方的任何空间都包含在您不想要的值中。希望这对其他人有帮助。詹姆士

于 2014-03-13T15:43:12.400 回答
0

解决方案的基本版本:

CSS

.sectionWrapper{
    background-color: #1E1E1E;
    padding: 10px 20px;
    color: #FF7B05;
    width: 100%
    height: 45px;
    min-height: 45px;

    margin-top: 30px;   
    position: relative;
    z-index: 10;
}
.sectionHeader{
}
.sectionEmbed {
}
.sectionFixed {
    background-color: #1E1E1E;
    padding: 10px 20px;
    color: #FF7B05;
    width: 100%;
    height: 45px;

    position: fixed;
    top: 0;
    left: 0;
    margin: 0;
}

HTML

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 sectionWrapper sectionEmbed">
    <div class="sectionHeader">Headers here</div>
</div>

jQuery

//check doc is ready
$(function() {
    $(window).on("scroll.sectionWrapper", function() {
        stickSections();
    });
});

//function stickSection
function stickSections()
{
    //detach the listener
    $(window).off("scroll.sectionWrapper");

    $scrollPos = $(window).scrollTop();
    $currentSticky = null;

    $('.sectionWrapper').each(function(){

        $(this).children().removeClass('sectionFixed');     

        if($scrollPos >= ($(this).offset().top - ($(this).height() - $(this).children().height() - 6)) ){
            $currentSticky = $(this);
        }
        else $(this).children().addClass('sectionEmbed');
    });

    //apply the fixed class to our scrollPos match
    if($currentSticky) $currentSticky.children().addClass('sectionFixed');

    //reattach the listener
    $(window).on("scroll.sectionWrapper", function() {
        stickSections();        
    });
}

例子

https://codepen.io/ZombiesByte/pen/EyYwVO

玩得开心 :)

于 2016-05-25T22:03:47.560 回答
0

如果 div 上方有带有粘性标题的内容,这并不总是有效: $thisSticky.css('transform', 'translateY(' + $newPosition+ 'px)');

但是这条线可以解决问题 //could just as easily use top instead of transform $thisSticky.css('top', $newPosition+ 'px');

于 2017-04-07T13:34:00.143 回答
0

@chris-spittles 提供的解决方案帮助了我很多,但我还想提供一个普通的 Javascript 解决方案。此外,我还添加了处理最后一个粘性的功能,以应对您不希望它在其内容区域之外继续固定的情况。

https://codepen.io/jamigibbs/pen/QZWjBy

const StickySubsections = (function(){
  let el

  return {
    elements: function () {
      return {
        stickies: [...document.querySelectorAll('.followMeBar')]
      }
    },

    init: function () {
      el = this.elements()
      this.load()
    },

    load: function () {
      this.setupStickyWrap()
      window.addEventListener('scroll', () => this.whenScrolling())
    },

    setupStickyWrap: function(){
      el.stickies.forEach((sticky, i) => {
        const stickyWrap = this.addWrap(sticky, 'sticky-wrap')
        const heightToTop = sticky.getBoundingClientRect().top + window.scrollY
        const outerHeight = sticky.offsetHeight

        stickyWrap.parentElement.id = `sticky-content-${i}`
        sticky.setAttribute('data-originalPosition', heightToTop)
        sticky.setAttribute('data-originalHeight', outerHeight)

        stickyWrap.style.height = outerHeight + 'px'
      })
    },

    addWrap: function(el, className, wrap = 'div') {
      const wrapper = document.createElement(wrap)
      wrapper.classList.add(className)
      el.parentNode.insertBefore(wrapper, el)
      wrapper.appendChild(el)
      return wrapper
    },

    elementExists: function(el){
      return typeof(el) != 'undefined' && el != null
    },

    stickyPosition: function(el){
      return el.getAttribute('data-originalPosition')
    },

    nextStickyPosition: function(current, next){
      return next.getAttribute('data-originalPosition') - current.getAttribute('data-originalHeight')
    },

    scrollingPositionTop: function(el){
      return el.getBoundingClientRect().top + window.scrollY
    },

    offsetTop: function(el){
      return el.getBoundingClientRect().top
    },

    scrollingPositionBottom: function(el){
      return el.getBoundingClientRect().bottom + window.scrollY
    },

    headerPosition: function(){
      return window.scrollY
    },

    bottomSectionHit: function(contentElement, sticky){
      const contentSection = document.getElementById(contentElement)
      const sectionBottom = contentSection.getBoundingClientRect().bottom + window.scrollY
      const stickyPositionScrolling = sticky.getBoundingClientRect().bottom + window.scrollY

      return stickyPositionScrolling >= sectionBottom
    },

    whenScrolling: function() {
      el.stickies.forEach((sticky, i) => {
        const nextSticky = el.stickies[i + 1]
        const prevSticky = el.stickies[i - 1]

        if (this.stickyPosition(sticky) <= this.headerPosition()) {
          sticky.classList.add('fixed')

          if (this.elementExists(nextSticky)) {

            while (this.scrollingPositionBottom(sticky) >= this.nextStickyPosition(sticky, nextSticky) + 50) {
              sticky.classList.add('absolute')
              sticky.style.top = this.nextStickyPosition(sticky, nextSticky)
            }

          // Handle last sticky element
          } else {
            if (this.bottomSectionHit(`sticky-content-${i}`, sticky)) {
              sticky.classList.remove('fixed')
            }
          }

        } else {

          sticky.classList.remove('fixed')

          if (this.elementExists(prevSticky) && window.scrollY <= this.stickyPosition(sticky)){
            prevSticky.classList.remove('absolute')
            prevSticky.removeAttribute('style')
          }
        }
      })
    }

  }
}())

StickySubsections.init()
于 2018-09-27T22:49:20.290 回答