美文网首页
原生JS手写一个可拖拽的进度条

原生JS手写一个可拖拽的进度条

作者: Thesand | 来源:发表于2020-09-17 10:54 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #progress {
            height: 20px;
            width: 500px;
            background-color: #ccc;
            border-radius: 8px;
            position: relative;
        }

        #progress_pill {
            position: absolute;
            border-radius: 8px 0 0px 8px;
            height: 100%;
            background-color: red;
            left: 0;
            top: 0;
        }

        #bar {
            position: absolute;
            top: -5px;
            left: 0;
            height: 30px;
            width: 20px;
            background-color: red;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div style="display: flex;padding: 200px;">
        <div id="progress">
            <div id="progress_pill">
            </div>
            <span id="bar">
            </span>
        </div>
        <span id="progress_text" style="margin-left: 20px;">0%</span>
    </div>

    <script>
        window.onload = function () {
            var progress = document.getElementById('progress')
            var progress_pill = document.getElementById('progress_pill')
            var progress_text = document.getElementById('progress_text')
            var bar = progress.children[1]
            var moveWidth = progress.offsetWidth - bar.offsetWidth
            bar.onmousedown = function (event) {
                var e = window.event || event
                var clientX = event.clientX - bar.offsetLeft
                console.log(progress.offsetWidth)
                document.body.onmousemove = function (event) {
                    event = event || window.event;
                    var moveX = event.clientX - clientX
                    if (moveX <= 0) {
                        moveX = 0
                    } else if (moveX >= moveWidth) {
                        moveX = moveWidth
                    }
                    bar.style.left = moveX + 'px'
                    progress_pill.style.width = moveX + 'px'
                    progress_text.innerHTML = parseInt(moveX / moveWidth * 100) + '%'
                    return false
                }
                document.body.onmouseup = function () {
                    document.body.onmousemove = null
                }
            }
        }
    </script>
</body>
</html>

相关文章

网友评论

      本文标题:原生JS手写一个可拖拽的进度条

      本文链接:https://www.haomeiwen.com/subject/dghlyktx.html