美化滾動條效果程式碼例項

螞蟻小編發表於2018-07-11

當前瀏覽器預設滾動條不夠美觀,不過可以模擬實現。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  margin: 0;
  padding: 0;
}
#div1 {
  position: relative;
  width: 500px;
  height: 500px;
  background: green;
  margin-left: 10px;
  overflow: hidden;
}
#div2 {
  width: 10px;
  height: 500px;
  background: black;
  position: absolute;
  right: 0px;
  top: 0px;
}
#div3 {
  width: 10px;
  height: 30px;
  background: red;
  position: absolute;
  top: 0;
  left: 0;
  cursor: pointer;
  border-radius: 5px;
}
#div4 {
  width: 485px;
  position: absolute;
  left: 0;
  top: 0;
}
</style>
<script>
window.onload = function() {
  var oDiv1 = document.getElementById("div1");
  var oDiv2 = document.getElementById("div2");
  var oDiv3 = document.getElementById("div3");
  var oDiv4 = document.getElementById("div4");
  oDiv3.onmousedown = function(ev) {
    var ev = ev || event;
    var disY = ev.clientY - this.offsetTop;
    var iMaxTop = oDiv2.offsetHeight - oDiv3.offsetHeight;
    document.onmousemove = function(ev) {
      var ev = ev || event;
      var T = ev.clientY - disY;
      if (T > iMaxTop) {
        T = iMaxTop;
      } else if (T < 0) {
        T = 0;
      }
      oDiv3.style.top = T + "px";
      //滾動條滾動的比例係數
      var iScale = T / iMaxTop;
      oDiv4.style.top = (oDiv1.offsetHeight - oDiv4.offsetHeight) * iScale + "px";
    }
    document.onmouseup = function() {
      document.onmousemove = document.onmouseup = null;
    }
    return false;
  }
}
</script>
</head>
<body>
  <!--3-1  1-2  2-3-->
  <div id="div1">
    <div id="div2">
      <div id="div3"></div>
    </div>
    <div id="div4">
      
    </div>
  </div>
</body>
</html>

相關文章