原生JS拖拽进度条改变元素透明度

2020-11-26 15:58:10 浏览数 (1)

今天要分享的是运用原生JS拖拽进度条改变元素透明度,效果如下:

以下是代码实现,欢迎大家复制粘贴。

代码语言:javascript复制
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS拖拽进度条改变元素透明度</title>
    <style>
        #parent {
            width: 400px;
            height: 20px;
            background: #CCC;
            position: relative;
            margin: 20px auto;
        }

        #div1 {
            width: 20px;
            height: 20px;
            background: red;
            cursor: pointer;
            position: absolute;
        }

        #div2 {
            width: 300px;
            height: 300px;
            margin: 0 auto;
            filter: alpha(opacity:0);
            opacity: 0;
            background: yellow;
        }
    </style>

    <script>
        window.onload = function () {

            var oDiv = document.getElementById('div1');
            var oParent = document.getElementById('parent');
            var oDiv2 = document.getElementById('div2');

            oDiv.onmousedown = function (ev) {

                var oEvent = ev || event;
                //计算鼠标相对滑块上的位置
                var disX = oEvent.clientX - oDiv.offsetLeft;

                document.onmousemove = function (ev) {

                    var oEvent = ev || event;
                    //计算滑块的动态left值
                    var l = oEvent.clientX - disX;

                    //限制拖拽范围
                    if (l < 0) {

                        l = 0;

                    } else if (l > oParent.offsetWidth - oDiv.offsetWidth) {

                        l = oParent.offsetWidth - oDiv.offsetWidth;
                    }

                    oDiv.style.left = l   'px';

                    //计算拖拽移动距离与可拖动总范围的比例
                    var scale = l / (oParent.offsetWidth - oDiv.offsetWidth);

                    //让Div2跟随鼠标的拖动逐渐显示与隐藏
                    oDiv2.style.filter = 'alpha(opacity:'   100 * scale   ')';
                    oDiv2.style.opacity = scale;

                };

                document.onmouseup = function () {

                    document.onmousemove = null;
                    document.onmouseup = null;
                };
            };
        };
    </script>
</head>

<body>
    <div id="parent">
        <div id="div1"></div>
    </div>
    <div id="div2"></div>
</body>

</html>

0 人点赞