博主信息
博文 5
粉丝 0
评论 0
访问量 5157
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
JavaScript实现进度条效果
P粉536129282
原创
676人浏览过

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

本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学