Javascript实现简洁的今年倒计时进度条

示例:

代码:

<style>
/*定义进度条的css格式*/
#myProgress {
  border: 1px solid #9BA1A7;
  width: 100%;
  background: #999;
  text-align: center;
 }
</style>

<!--显示进度条-->
<div id="myProgress"></div>

<script>
//获取当前时刻和今年年底时刻
var date = new Date(); 
var year = date.getFullYear(); 
var date2 = new Date(year, 11, 31, 23, 59, 59,999);//
var date1 = new Date(year,0);

//得到当前时间占全年时间的百分比
var pec = 100*(date - date1)/(date2-date1);

//得到今年还剩余的天数
var days = (date2-date)/24/60/60/1000;

days = days.toFixed(0);
pec = pec.toFixed(2);

var elem = document.getElementById("myProgress");
var magic = "linear-gradient(to right, #fff ,#3c5aee " + pec + "% , #FFFFFF " + pec + "% )";
elem.style.background = magic;
elem.innerText =`今年已经过了${pec}%,还剩${days}天`;
</script>