<section class="wrapper">
  <div class="empty-content"></div>
  <p id="title" class="center-title">Sticky Title</p>
</section>
* {
  padding: 0;
  margin: 0;
}

html, body {
  height: 100%;
}

.wrapper {
  background-color: #F2F6FC;
  height: 200%;
  width: 300px;
  position: relative;
}

.empty-content {
  height: 50px;
}

.center-title {
  width: 100%;
  background-color: #409EFF;
  color: white;
  text-align: center;
}

.sticky-top {
  position: sticky;
  top: 0;
  background-color: #67C23A;
  color: white;
  text-align: center;
}
View Compiled
window.onload = function() {
  // 获取目标节点
  const targetElement = document.getElementById("title");
  
  window.onscroll = _.throttle(() => {
    const reactObj = targetElement.getBoundingClientRect();
    
    if (reactObj.top <= 0) {
      console.log(1)
      targetElement.setAttribute('class', "sticky-top");
    } else {
      targetElement.setAttribute('class', "center-title")
    }
  }, 200);
};
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js