前言:
1、搞出今天的日期
2、搞出今天所在周的时间集合
<!DOCTYPE html>
<html lang="zh">
<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" />
<title>Document</title>
<style>
*{margin: 0;padding: 0;}
.box{
margin: 20px;
position: relative;
padding: 0 20px;
box-sizing: border-box;
display: inline-block;
}
.btn{
position: absolute;
top: 2px;
font-family: simsun;
cursor: pointer;
}
.btnleft{
left: 0;
}
.btnright{
right: 0;
}
</style>
</head>
<body>
<h4></h4>
<div class="box">
<p>
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
</p>
<div class="btn btnleft"><</div>
<div class="btn btnright">></div>
</div>
<script src='jquery.min.js'></script>
<script>
var today = ''; //默认今天的日期(ajax传参使用)
var clen= 7;
var currentFirstDate= '';
var weekDayArr = []; //今天所在这一周的集合
function todaytime() {
let now = new Date();
let year = now.getFullYear(),
month = now.getMonth() + 1,
date = now.getDate();
month = checkTime(month);
date = checkTime(date);
today = year + '-' + month + '-' + date;
$('h4').text('今天的日期是'+today);
}
function checkTime(i) {
if(i < 10) {
i = "0" + i
}
return i
}
todaytime(); //搞出今天的年月日
function formatDate(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = this.checkTime(month);
var day = date.getDate();
day = this.checkTime(day);
return year + '-' + month + '-' + day;
}
function addDate(date, n) {
date.setDate(date.getDate() + n);
return date;
}
function showhtml(arr){
var shtml ='';
for(var i=0,len=arr.length;i<len;i++){
shtml+='<span>'+arr[i].time.substr(8,2)+'</span> ';
}
$('p').html(shtml);
}
function setDate(date) {
var week = date.getDay() - 1;
date = addDate(date, week * -1);
currentFirstDate = new Date(date);
for(var i = 0; i < this.clen; i++) {
weekDayArr.push({
"time": formatDate(i == 0 ? date : this.addDate(date, 1)),
})
}
console.log(weekDayArr);
showhtml(weekDayArr);
}
setDate(new Date());//搞出今天所在周的时间集合
$(".box").on("click",".btnleft",function(){
weekDayArr = []
setDate(addDate(currentFirstDate, -7));
})
$(".box").on("click",".btnright",function(){
weekDayArr = []
setDate(addDate(currentFirstDate, 7));
})
</script>
</body>
</html>