The head of sticky effect

Primer

Recently I came across one effect: when the page is scrolled, when the specified elements beyond the visible area needs to be fixed at the top of the viewing area. Then think of another way, this unified record it.

A thought

This line of thinking is more common, very early in use, specifically listen for scrolling events specified elements to calculate the position of the top of the visible area in event processing program, change the position property elements beyond the visible area from the original document flow.

The point to note here are:

  • After the element out of the document flow, originally occupied the position, need to be addressed, otherwise the contents of the elements behind will suddenly move up phenomenon.
  • Scroll event processing frequently triggered when leaving the page remember to lift the event binding.

This is an example of a page , the mobile access terminal follows:

60-qr-fixed

Examples of the main code

<!doctype html>
<html lang="en">
  <head></head>
  <body>
    <div id="titleHolder"></div>
    <h2 class="title" id="title">需动态固定的元素</h2>
    <div>内容</div>
  </body>
</html>
  body {
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }
  .title-holder,
  .title {
    top: 0;
    margin: 0;
    width: 100%;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background-color: #fff;
  }
  var scrollObj = document.querySelector('body');
  var targetHolderEle = document.querySelector('#titleHolder');
  var targetEle = document.querySelector('#title');
  var scrollMark = null;
  function dealScroll() {
    if (scrollMark) {
      clearTimeout(scrollMark);
    }

    scrollMark = setTimeout(() => {
        var topDistance = 0;
        // getBoundingClientRect 有些浏览器不支持
        if (targetHolderEle.getBoundingClientRect) {
          var pos = targetHolderEle.getBoundingClientRect();
          topDistance = pos.top;
        } else {
          var eleTop = targetHolderEle.offsetTop;
          topDistance = eleTop - scrollObj.scrollTop;
        }
        if (topDistance < 1) {
          targetHolderEle.setAttribute('class','title-holder');
          targetEle.style.position = 'fixed';
        } else {
          targetHolderEle.setAttribute('class','');
          targetEle.style.position = 'static';
        }
    }, 10);
  }

  function listenScroll() {
    scrollObj.addEventListener('scroll', dealScroll);
  }

Ideas two

Use the new positionvalue sticky. I think this is because the thought had written position property values sticky this summary. In this manner a relatively reduced number of code, compatibility issues, see the requirements of practical application scenarios.

This is an example of a page , the mobile access terminal follows:

60-qr-sticky

Reference material

Guess you like

Origin www.cnblogs.com/thyshare/p/12204113.html