JS實現拖拽進度條改變元素透明度

今天要分享的是運用原生JS拖拽進度條改變元素透明度,效果如下:

以下是代碼實現,歡迎大傢復制粘貼。

<!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>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: