公告:“业余草”微信公众号提供免费CSDN下载服务(只下Java资源),关注业余草微信公众号,添加作者微信:xttblog2,发送下载链接帮助你免费下载!
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云
圆环倒计时我们经常见到,实现的方法也有很多种。但是本文将介绍一种全新的实现方式,使用SVG来实现倒计时功能。
本文主要用到了SVG的stroke-dasharray和stroke-dashoffset特性。下图是倒计时运行效果:
下面说说相关的实现代码。css实现代码如下:
svg {
transform: rotate(-0.05deg);
}
circle {
transition: stroke-dasharray .2s;
}
.time-count-x {
line-height: 1.5;
position: relative;
}
.time-second {
position: absolute;
top: 50%; left: 0; right: 0;
margin-top: -.75em;
text-align: center;
font-size: 100px;
}
相关html代码如下:
<div id="timeCountX" class="time-count-x">
<svg width="440" height="440" viewBox="0 0 440 440" class="center">
<defs>
<linearGradient x1="1" y1="0" x2="0" y2="0" id="gradient1">
<stop offset="0%" stop-color="#e52c5c"></stop>
<stop offset="100%" stop-color="#ab5aea"></stop>
</linearGradient>
<linearGradient x1="1" y1="0" x2="0" y2="0" id="gradient2">
<stop offset="0%" stop-color="#4352f3"></stop>
<stop offset="100%" stop-color="#ab5aea"></stop>
</linearGradient>
</defs>
<g transform="matrix(0,-1,1,0,0,440)">
<circle cx="220" cy="220" r="170" stroke-width="50" stroke="#f0f1f5" fill="none" stroke-dasharray="1069 1069"></circle>
<circle cx="220" cy="220" r="170" stroke-width="50" stroke="url('#gradient1')" fill="none" stroke-dasharray="1069 1069"></circle>
<circle cx="220" cy="220" r="170" stroke-width="50" stroke="url('#gradient2')" fill="none" stroke-dasharray="534.5 1069"></circle>
</g>
</svg>
<span id="timeSecond" class="time-second"></span>
</div>
最后是相关JavaScript代码:
var eleCircles=document.querySelectorAll("#timeCountX circle");
var eleTimeSec=document.getElementById("timeSecond");
var perimeter=Math.PI*2*170;
var circleInit=function(){
if(eleCircles[1]){
eleCircles[1].setAttribute("stroke-dasharray","1069 1069")
}
if(eleCircles[2]){
eleCircles[2].setAttribute("stroke-dasharray",perimeter/2+" 1069")
}
eleTimeSec.innerHTML=""
};
var timerTimeCount=null;
var fnTimeCount=function(b){
if(timerTimeCount){
return
}
var b=b||10;
var a=function(){
var c=b/10;
if(eleCircles[1]){
eleCircles[1].setAttribute("stroke-dasharray",perimeter*c+" 1069")
}
if(eleCircles[2]&&b<=5){
eleCircles[2].setAttribute("stroke-dasharray",perimeter*c+" 1069")
}
if(eleTimeSec){
eleTimeSec.innerHTML=b
}
b--;
if(b<0){
clearInterval(timerTimeCount);
timerTimeCount=null;
alert("时间到!");
circleInit()
}
};
a();
timerTimeCount=setInterval(a,1000)
};
fnTimeCount();
整个案例的代码非常少,有喜欢的朋友可以将代码保存到html中,运行一下,体验体验实际效果。

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!
本文原文出处:业余草: » SVG实现多彩圆环倒计时效果