ASCII码 ASCII码

JavaScript实现进度条效果

发布于:2022-03-04 11:21:35  栏目:技术文档

本文实例为大家分享了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>`

相关推荐
阅读 +