×

javascript:拖拽进度条改变模块透明度

作者:jiang2021.10.20来源:Web前端之家浏览:3676评论:0
关键词:js

今天分享一个原生javascript小应用:拖拽进度条改变元素透明度。直接上DEMO。

<!DOCTYPE html>
<html>
 
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>javascript:拖拽进度条改变模块透明度 - Web前端之家www.jiangweishan.com</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"><p>欢迎来到Web前端之家!!!!</p></div>
</body>
 
</html>

试试吧!!

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/js20211020a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: