JavaScript实现圆形进度条效果
本文实例为大家分享了JavaScript实现圆形进度条效果的具体代码,供大家参考,具体内容如下
<!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> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <style> .itemwait{ position:absolute; top : 0; bottom:0; left:0; right:0; margin: 0 auto; } .progress{ stroke-dasharray: 251; stroke-dashoffset: 0; /* stroke-dasharray: 虚线 stroke-dashoffset: 偏移间隔 */ } </style> </head> <body> <svg width="200" height="200" version="1.1" class='itemwait'> <circle class='progress' cx="100" cy="50" r="40" stroke="pink" stroke-width="5" fill="transparent" /> <text class='text' x="100" y="50" fill='pink' text-anchor='middle' alignment-baseline='middle'>开始加载</text> </svg> </body> <script async type='text/javascript'> //js代码见下文 </script> </html>
1.原生js实现
const loadingArr=[1,2,10,20,40,70,90,100] let index=0 var timer=setInterval(()=【本文由:香港云服务器http://www.558cloud.com提供,感谢】>{ let total=document.querySelector('.progress').getTotalLength(); let progress=document.querySelector('.progress') console.log(typeof total) progress.style.strokeDashoffset=(total)*(1-loadingArr[index]/100) if(index<=loadingArr.length){ document.querySelector('.text').textContent=`${loadingArr[index]}%` } index++ if(index===loadingArr.length){ clearInterval(timer) document.querySelector('.text').textContent='加载完成' } },500)
2.jQuery实现
let index = 0 var $circle = $('.progress'); var r = $circle.attr('r'); var timer = setInterval(() => { var total = Math.PI * (r * 2); var pct = (1-index / 100) * total; console.log(typeof pct,pct) if (index <= 100) { $('.text').text(`${index}%`); $circle.css({ strokeDashoffset: pct }); } index = index + 10 if (index > 100) { $('.text').text('加载完成'); clearInterval(timer) } }, 500)
3.最初按照自己的想法实现
const loadingArr=[1,2,10,20,40,70,90,100] let index=0 var timer=setInterval(()=>{ let total=document.querySelector('.progress').getTotalLength(); let progress=document.querySelector('.progress') console.log(typeof total) progress.style.strokeDashoffset=(total)*(1-loadingArr[index]/100) $('.text').text(function(){ if(index<=loadingArr.length){ return `${loadingArr[index]}%` } }) index++ if(index===loadingArr.length){ clearInterval(timer) $('.text').text('加载完成') } },500)
总结
知识点:svg绘图、js原生操作、jQuery
- stroke-dasharray: 虚线
- stroke-dashoffset: 偏移间隔
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持hwidc。