前端进度条

html部分

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            padding0;
            margin0;
        }
        
        #progress {
            width800px;
            height40px;
            line-height40px;
            /*background: #e8e8e8;*/
            margin100px auto;
            positionrelative;
        }
        
        #progress_bar {
            width700px;
            height100%;
            background#727272;
            border-radius10px;
            positionrelative;
        }
        
        #progress_bar_fg {
            width0px;
            height100%;
            background#ff960d;
            border-top-left-radius10px;
            border-bottom-left-radius10px;
        }
        
        span {
            width25px;
            height50px;
            positionabsolute;
            top-5px;
            left0px;
            border-radius10px;
            backgroundorange;
        }
        
        #value {
            positionabsolute;
            top0;
            right0;
        }
    </style>
</head>

<body>
    <div id="progress">
        <div id="progress_bar">
            <div id="progress_bar_fg"></div>
            <span id="mask"></span>
        </div>
        <div id="value">0%</div>
    </div>
    <script src="index.js"></script>
</body>

</html>
js部分
 
window.onload = function() {
    let bar = document.getElementById("progress_bar")
    let fg = document.getElementById("progress_bar_fg")
    let mask = document.getElementById("mask")
    let value = document.getElementById("value")

    //监听鼠标按下
    mask.onmousedown = function(event) {
        let e = event || window.event
            //获取mask初始位置
            // console.log(mask.offsetLeft);
            // console.log(e.clientX);
        let offsetleft = e.clientX - mask.offsetLeft
            //console.log(offsetleft);
            //监听鼠标移动(在按下事件内)
        document.onmousemove = function() {
            let e = window.event || arguments[0]
                //获取鼠标移动距离
            let x = e.clientX - offsetleft
                //mask移动

            if (x < 0) {
                x = 0
            } else if (x >= bar.offsetWidth - mask.offsetWidth) {
                x = bar.offsetWidth - mask.offsetWidth
            }
            mask.style.left = x + "px"
            fg.style.width = x + "px"
            value.innerText = parseInt(x / (bar.offsetWidth - mask.offsetWidth) * 100) + "%"

            return false

        }

        //监听鼠标抬起(也在鼠标按下事件)
        document.onmouseup = function() {
            //销毁移动事件
            document.onmousemove = null
        }


    }



}
 
posted @ 2020-06-16 22:33  岱宗如何  阅读(397)  评论(0编辑  收藏  举报