JS 新闻 鼠标滚动 滚动条

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/boonyaxnn/article/details/89217762

一、html代码

<div class="box"...>

二、css样式

<style>
    * {
        margin: 0;
        padding: 0;
    }
    .box {
        margin: 50px auto;
        border: 2px solid skyblue;
        height: 500px;
        width: 500px;
        position: relative;
        overflow: hidden;
    }
    .bar {
        position: absolute;
        height: 500px;
        width: 20px;
        right: 0;
        top: 0;
        background-color: gray;
    }
    .content {
        padding: 20px;
        position: absolute;
    }
    .slideBar {
        height: 60px;
        width: 20px;
        background-color: blue;
        position: absolute;
        top: 0;
        right: 0;
    }
</style>

三、开始写js

1、首先获取界面元素

   var box = document.querySelector('.box');
   var content = document.querySelector('.content');
   var bar = document.querySelector('.bar');
   var slideBar = document.querySelector('.slideBar');

2、设置滚动条的高度

   ①计算整个内容的高度与显示屏高度的比例

    var rate = content.clientHeight / box.clientHeight;

  ②根据比例的关系设置滚动条的高度

   var hight = bar.clientHeight / rate;
   slideBar.style.height = hight + 'px';

     设置开关判断是否可以移动

     var flag = false;

3、鼠标按下事件绑定给滚动条

   var delY = 0;
   slideBar.onmousedown = function () {
          flag = true;
        delY = event.clientY - slideBar.offsetTop;
        //取消节点默认行为
        if (event.preventDefault) {
           event.preventDefault();
         } else {
          event.returnValue = false;
         }
    };
   /* 改变距离 */
    var y = 0;
    function changeDis() {
           /* 范围校验 */
        if (y < 0) {
            y = 0;
         }
        if (y > bar.clientHeight - slideBar.clientHeight) {
          y = bar.clientHeight - slideBar.clientHeight;
         }
           slideBar.style.top = y + 'px';
           content.style.top = -y * rate + 'px';
      }

4、鼠标移动事件绑定给滚动背景box

     box.onmousemove = function () {
         if (flag) {
            y = event.clientY - delY;
           changeDis();
          }
       };

5、鼠标抬起事件可以绑定给document

    document.onmouseup = function () {
           flag = false;
    };

6、给box绑定滚轮事件

function wheelScroll(event) {
    console.log('11111111111111111');
    //向上滚动时 输出1  向下滚动时输出-1
    event = event || window.event;
    console.log(event);
    //取消节点默认行为 box滑动 外层的body也会滑动
    if (event.preventDefault) {
        event.preventDefault();
    } else {
        event.returnValue = false;
    }
    //判断浏览器的类型
    var dircetion = 0;
    if (event.wheelDelta) {
        dircetion = event.wheelDelta > 0 ? 1 : -1;
    } else {
        dircetion = event.detail < 0 ? 1 : -1;
    }
    //鼠标滚动距离的累加
    y += -dircetion * 10;
    console.log(y);
    /*
     范围校验
     */
    changeDis();
}
box.onmousewheel = wheelScroll;

try {
    box.addEventListener('DOMMouseScroll', wheelScroll);
} catch (e) {
    //  console.log(e);
}

效果图:

猜你喜欢

转载自blog.csdn.net/boonyaxnn/article/details/89217762