Targeting position:sticky elements that are currently in a 'stuck' state

后端 未结 5 1990
名媛妹妹
名媛妹妹 2020-12-04 17:26

position: sticky works on some mobile browsers now, so you can make a menu bar scroll with the page but then stick to the top of the viewport whenever the user scrolls past

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 17:42

    A compact way for when you have an element above the position:sticky element. It sets the attribute stuck which you can match in CSS with header[stuck]:

    HTML:

    
    
    ...
    ...

    JS:

    if (typeof IntersectionObserver !== 'function') {
      // sorry, IE https://caniuse.com/#feat=intersectionobserver
      return
    }
    
    new IntersectionObserver(
      function (entries, observer) {
        for (var _i = 0; _i < entries.length; _i++) {
          var stickyHeader = entries[_i].target.nextSibling
          stickyHeader.toggleAttribute('stuck', !entries[_i].isIntersecting)
        }
      },
      {}
    ).observe(document.getElementById('logo'))
    

提交回复
热议问题