温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用JavaScript实现进度条效果

发布时间:2021-10-26 14:31:56 来源:亿速云 阅读:125 作者:iii 栏目:开发技术

本篇内容主要讲解“怎么用JavaScript实现进度条效果”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用JavaScript实现进度条效果”吧!

具体内容如下

这次的效果图如下:

怎么用JavaScript实现进度条效果

这个案例做起来不难,在我练习的时候,新知识点是使用window.getComputedStyle()函数获取元素的宽度值

总的思路是在一个div盒子初始放入一个宽度为0的div盒子,然后在按钮的onclick回调函数中使用定时器改变其宽度值

代码如下:

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #container {
            width: 500px;
            height: 200px;
            margin: 50px auto;
            position: relative;
        }

        #box {
            width: 260px;
            height: 30px;
            border: 1px pink solid;
            border-radius: 16px;
            margin-bottom: 20px;
            padding: 1px;
            overflow: hidden;
        }

        #cont {
            width: 0;
            height: 100%;
            background-color: pink;
            border-radius: 16px;
        }

        #btn {
            position: absolute;
            margin-left: 110px;
            width: 50px;
            height: 30px;
        }


        #text {
            display: block;
            position: relative;
            left: 120px;
            margin-bottom: 20px;
        }

    </style>
</head>

<body>
    <div id="container">
        <div id="box" data-content-before="22">
            <div id="cont"></div>
        </div>
        <div id="text">0%</div>
        <button id="btn">提交</button>
    </div>
    <script>
        let box = document.getElementById("box");
        let btn = document.getElementById("btn");
        let cont = document.getElementById("cont");
        let text = document.getElementById("text");

        function getstyle(obj, name) {
            if (window.getComputedStyle) {
                return window.getComputedStyle(obj, null)[name];
            }
            else {
                return obj.currentStyle[name];
            }
        }

        btn.onclick = function () {
            let ini = 0;
            let num = setInterval(() => {

                let tem = parseInt(window.getComputedStyle(cont, null)["width"]);
                let now = tem + 26;

                if (tem >= 260) {
                    console.log(now);
                    clearInterval(num);
                    return;
                }
                
                cont.style.width = now + "px";
                ini = ini + 10;
                text.innerText = ini + "%";

            }, 80);
        }
    </script>

</body>

</html>

到此,相信大家对“怎么用JavaScript实现进度条效果”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI