javascript实现滚动条效果

网络编程 2021-07-04 15:02www.168986.cn编程入门
这篇文章主要为大家详细介绍了javascript实现滚动条效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了javascript实现滚动条效果的具体代码,供大家参考,具体内容如下

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
<style>
 html, body {
  height: 100%;
  margin: 0;
 }
 #container {
  position: absolute;
  : 50px;
  left: 100px;
  height: 400px;
  width: 150px;
  background-color: aliceblue;
  padding: 2rem;
  box-sizing: border-box;
  /必须属性,否则给scrollTop赋值无效/
  overflow-y: hidden;
  position: relative;
  padding-right: 30px;
 }
 .scrollbar {
  height: 50px;
  width: 10px;
  border-radius: 20px;
  background: #c;
  position: absolute;
  right: 0;
 }
</style>
 <script>
 window.onload = function () {
  var scrollbar = document.querySelector('.scrollbar');
  var container = scrollbar.parentNode;
  container.scrollbar = scrollbar;
  container.ratio =
   (container.scrollHeight - container.offsetHeight) / (container.offsetHeight - scrollbar.offsetHeight);
  container.addEventListener('mousewheel', function(e) {
   this.scrollTop += e.deltaY;
   this.scrollbar.style. = (this.scrollTop + this.scrollTop / this.ratio) + 'px';
  });
  container.addEventListener('mousedown', function (e) {
   if (e.target === this.scrollbar) {
    this.prevY = e.pageY;
   }
  });
  container.addEventListener('mouseup', function (e) {
   this.prevY = null;
  });
  container.addEventListener('mousemove', function (e) {
   if (this.prevY) {
    this.scrollTop += (e.pageY - this.prevY)  this.ratio;
    this.scrollbar.style. = (this.scrollTop + this.scrollTop / this.ratio) + 'px';
    this.prevY = e.pageY;
   }
   e.preventDefault();
  });
 }
 </script>
</head>
<body>
 <div id="container">
  <div class="scrollbar"></div>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
  <p>fefe</p>
 </div>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by