原理

  • 对滚动条事件的监听
  • 利用fixed布局实现组件的滚动

code

<!DOCTYPE html>
<html lang="zh-CN"
<head>
  <meta charset="utf-8">
</head>
<style>
#div1{
  background-color: red;
  width: 100px;
  height: 100px;
  position: fixed;
  top: 0;
}
#div2{
  background-color: blue;
  width: 100px;
  height: 100px;
  position: fixed;
  top: 100px;
}
body{
  height: 4000px;
}
</style>
<body>
  <div id="div1"></div>
  <div id="div2"></div>
  <script type="text/javascript">
  window.onscroll = function(){
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    document.getElementById("div1").style.top = scrollTop/10 + "px";
    document.getElementById("div2").style.top = 100+scrollTop/10 *3 +"px";
  }
  </script>
</body>
</html>