用于检测位置:粘滞何时触发的事件Demo IntersectionObserver

问题描述 投票:33回答:6

我正在使用新的position: stickyinfo)创建类似iOS的内容列表。

它运行良好,并且比以前的JavaScript替代方法(example)优越得多,但是据我所知,触发该事件时不会触发任何事件,这意味着当该栏到达页面顶部时,我无法执行任何操作,与以前的解决方案不同。

当具有stuck的元素到达页面顶部时,我想添加一个类(例如position: sticky)。有没有办法用JavaScript监听呢? jQuery的用法很好。

可以找到正在使用的新position: sticky的演示here

javascript jquery html css position
6个回答
14
投票

[如果有人通过Google到达这里,他们自己的工程师中就有一个使用IntersectionObserver,自定义事件和哨兵的解决方案:

https://developers.google.com/web/updates/2017/09/sticky-headers


7
投票

[DemoIntersectionObserver(技巧):

// get the sticky element
const stickyElm = document.querySelector('header')

const observer = new IntersectionObserver( 
  ([e]) => e.target.classList.toggle('isSticky', e.intersectionRatio < 1),
  {threshold: [1]}
);

observer.observe(stickyElm)
body{ height: 200vh; font:20px Arial; }

section{
  background: lightblue;
  padding: 2em 1em;
}

header{
  position: sticky;
  top: -1px;                       /* ➜ the trick */

  padding: 1em;
  padding-top: calc(1em + 1px);    /* ➜ compensate for the trick */

  background: salmon;
  transition: .1s;
}

/* styles for when the header is in sticky mode */
header.isSticky{
  font-size: .8em;
  opacity: .5;
}
<section>Space</section>
<header>Sticky Header</header>

top值必须为-1px,否则元素将永远不会与浏览器窗口的顶部相交(因此永远不会触发相交观察器)。

为了解决隐藏内容的此1px,应在粘性元素的边框或填充处添加额外的1px空间。

具有老式scroll事件监听器的演示:

  1. auto-detecting first scrollable parent
  2. Throttling the scroll event
  3. 关注点分离的功能组成
  4. 事件回调缓存:scrollCallback(能够根据需要取消绑定)

// get the sticky element
const stickyElm = document.querySelector('header');

// get the first parent element which is scrollable
const stickyElmScrollableParent = getScrollParent(stickyElm);

// save the original offsetTop. when this changes, it means stickiness has begun.
stickyElm._originalOffsetTop = stickyElm.offsetTop;


// compare previous scrollTop to current one
const detectStickiness = (elm, cb) => () => cb & cb(elm.offsetTop != elm._originalOffsetTop)

// Act if sticky or not
const onSticky = isSticky => {
   console.clear()
   console.log(isSticky)
   
   stickyElm.classList.toggle('isSticky', isSticky)
}

// bind a scroll event listener on the scrollable parent (whatever it is)
// in this exmaple I am throttling the "scroll" event for performance reasons.
// I also use functional composition to diffrentiate between the detection function and
// the function which acts uppon the detected information (stickiness)

const scrollCallback = throttle(detectStickiness(stickyElm, onSticky), 100)
stickyElmScrollableParent.addEventListener('scroll', scrollCallback)



// OPTIONAL CODE BELOW ///////////////////

// find-first-scrollable-parent
// Credit: https://stackoverflow.com/a/42543908/104380
function getScrollParent(element, includeHidden) {
    var style = getComputedStyle(element),
        excludeStaticParent = style.position === "absolute",
        overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/;

    if (style.position !== "fixed") 
      for (var parent = element; (parent = parent.parentElement); ){
          style = getComputedStyle(parent);
          if (excludeStaticParent && style.position === "static") 
              continue;
          if (overflowRegex.test(style.overflow + style.overflowY + style.overflowX)) 
            return parent;
      }

    return window
}

// Throttle
// Credit: https://jsfiddle.net/jonathansampson/m7G64
function throttle (callback, limit) {
    var wait = false;                  // Initially, we're not waiting
    return function () {               // We return a throttled function
        if (!wait) {                   // If we're not waiting
            callback.call();           // Execute users function
            wait = true;               // Prevent future invocations
            setTimeout(function () {   // After a period of time
                wait = false;          // And allow future invocations
            }, limit);
        }
    }
}
header{
  position: sticky;
  top: 0;

  /* not important styles */
  background: salmon;
  padding: 1em;
  transition: .1s;
}

header.isSticky{
  /* styles for when the header is in sticky mode */
  font-size: .8em;
  opacity: .5;
}

/* not important styles*/

body{ height: 200vh; font:20px Arial; }

section{
  background: lightblue;
  padding: 2em 1em;
}
<section>Space</section>
<header>Sticky Header</header>

这里是使用第一种技术的React component demo


5
投票

当前没有本机解决方案。参见Targeting position:sticky elements that are currently in a 'stuck' state。但是,我有一个CoffeeScript解决方案,可与本机position: sticky和实现粘性行为的polyfill一起使用。

将“粘性”类添加到您想成为粘性的元素中:

.sticky {
  position: -webkit-sticky;
  position: -moz-sticky;
  position: -ms-sticky;
  position: -o-sticky;
  position: sticky;
  top: 0px;
  z-index: 1;
}

CoffeeScript监视“粘性”元素的位置,并在它们处于“粘性”状态时添加“ stuck”类:

$ -> new StickyMonitor

class StickyMonitor

  SCROLL_ACTION_DELAY: 50

  constructor: ->
    $(window).scroll @scroll_handler if $('.sticky').length > 0

  scroll_handler: =>
    @scroll_timer ||= setTimeout(@scroll_handler_throttled, @SCROLL_ACTION_DELAY)

  scroll_handler_throttled: =>
    @scroll_timer = null
    @toggle_stuck_state_for_sticky_elements()

  toggle_stuck_state_for_sticky_elements: =>
    $('.sticky').each ->
      $(this).toggleClass('stuck', this.getBoundingClientRect().top - parseInt($(this).css('top')) <= 1)

注意:此代码仅适用于垂直粘性位置。


2
投票

[Chrome添加position: sticky后,发现它是not ready enoughrelegated to to --enable-experimental-webkit-features flag。保罗·爱尔兰said in February“功能处于奇怪的边缘状态atm”。

我一直在使用the polyfill,直到感到头疼为止。这样做的时候效果很好,但是在某些情况下(例如CORS问题),并且通过对所有CSS链接执行XHR请求并为浏览器忽略的“位置:粘性”声明重新解析它们,从而减慢了页面加载速度。

现在我正在使用ScrollToFixed,比起StickyJS,我更喜欢它,因为它不会用包装纸弄乱我的布局。


2
投票

我想出了这个解决方案,它就像一个魅力,很小。 :)

不需要额外的元素。

它确实在窗口滚动事件上运行,尽管它的缺点很小。

var _$stickies = [].slice.call(document.querySelectorAll('.sticky'));

_$stickies.forEach(function(_$sticky){
    if (CSS.supports && CSS.supports('position', 'sticky')) {
        apply_sticky_class(_$sticky);

        window.addEventListener('scroll', function(){
            apply_sticky_class(_$sticky);
        })
    }
})

function apply_sticky_class(_$sticky){
    var currentOffset = _$sticky.getBoundingClientRect().top;
    var stickyOffset = parseInt( getComputedStyle(_$sticky).top.replace('px','') );
    var isStuck = currentOffset <= stickyOffset;

    _$sticky.classList.toggle('js-is-sticky', isStuck);
}

注意:此解决方案不考虑具有底部粘性的元素。这仅适用于粘性标头之类的东西。不过,它可能可以进行调整以考虑底部粘性。


1
投票

我知道问题提出已经有一段时间了,但是我找到了一个很好的解决方案。插件stickybits在支持的地方使用position: sticky,并在元素“卡住”时将其应用于类。我最近使用它取得了不错的效果,并且在撰写本文时,它是活跃的开发(对我来说是一个加分):)

© www.soinside.com 2019 - 2024. All rights reserved.