1、先看效果图哦!
注:文章底部有源码
2、关键代码解读
var targets = $(".targetTime"); // 获取到每个条状图的div
var dayMand = $(".year h1"); // 获取存放标题的h1标签
for (var i = 0; i < targets.length; i++) { //遍历
targets.eq(i).css({width:"0"}).animate({width:data[i][8]+"%","backgroundColor": data[i][7]},1000); // 动画
targets.eq(i).html("还有" + data[i][9] + "天"); // 设置剩余天数文本
dayMand.eq(i).html(data[i][6]); // 设置标题文本
}
动画那一行代码详细解读:
targets.eq(i) // 具体的某一条条状图
.css({width:”0”}) // 设置起始宽度为0,为后面的动画起点做准备
.animate({width:data[i][8]+”%”,”backgroundColor”: data[i][7]},1000);//动画,参数1,需要改变的属性,本案例中改变的是宽度和背景(取自数组),参数2,动画时间1000毫秒内执行。
注:文章底部有源码
3、逻辑实现步骤
3.1 创建保存目标日期的二维数组
3.2 获取从今天到过年这段时间的毫秒数
3.3 获取从今天到节日的毫秒数
3.4 求出3.3和3.2的比值,作为柱状图的长度
3.5 用动画效果设置柱状图的长度,就大功告成啦!
4、所有源码
<script src="./js/jquery-1.12.4.min.js"></script>
<script src="./js/jquery.animate-colors-min.js"></script>
以上两个js库请自行下载哦。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./js/jquery-1.12.4.min.js"></script>
<script src="./js/jquery.animate-colors-min.js"></script>
<style>
.year {
width: 80%;
margin: 20px;
border: 2px solid #000;
overflow: hidden;
}
.targetTime {
height: 50px;
width: 13%;
background-color: pink;
margin: -2px;
border: 2px solid #000;
line-height: 50px;
text-align: right;
font-size: 20px;
color: white;
}
h1 {
margin: 0;
padding: 0;
}
</style>
<title>Document</title>
<script>
$(function () {
var data = [[2017, 10, 28, 0, 0, 0, "测试", "gold"],
[2017, 10, 11, 0, 0, 0, "双十一", "green"],
[2018, 1, 16, 0, 0, 0, "过年", "red"],
[2017,9,1,0,0,0,"国庆节","orange"],
[2017,11,15,0,0,0,"传智毕业","pink"],
[2017,10,21,0,0,0,"PHP毕业","yellow"],
[2017,12,19,0,0,0,"python3期毕业","blue"],
[2017,9,6,0,0,0,"节后上课","blue"]];
var yearTime = new Date(2018, 1, 16, 0, 0, 0);
var str = "";
for (var i in data) {
var target = data[i];
var targetTime = new Date(target[0], target[1], target[2], target[3], target[4], target[5]);
var nowTime = new Date();
var offsetTime = targetTime - nowTime;
var offsetDay = parseInt(offsetTime / 1000 / 86400);
var lastTime = yearTime - nowTime;
var percentage = offsetTime / lastTime;
percentage = parseInt(percentage * 100);
data[i].push(percentage);
data[i].push(offsetDay);
str += '<h1>生日</h1><div class="targetTime"></div>';
}
$(".year").html(str);
var targets = $(".targetTime");
/* targets.css({"marginLeft":-1000}).animate({"marginLeft":0},1000); */
var dayMand = $(".year h1");
console.log(targets);
for (var i = 0; i < targets.length; i++) {
/* targets.eq(i).css({ "width": data[i][8] + "%", "backgroundColor": data[i][7] }); */
targets.eq(i).css({width:"0"}).animate({width:data[i][8]+"%","backgroundColor": data[i][7]},1000);
targets.eq(i).html("还有" + data[i][9] + "天");
dayMand.eq(i).html(data[i][6]);
}
})
</script>
</head>
<body>
<div class="year">
<div class="targetTime">
</div>
</div>
</body>
</html>
5、视频地址
视频后面再补啦!!嘎嘎~