gpt4 book ai didi

javascript - 日历 - 编辑脚本

转载 作者:行者123 更新时间:2023-12-02 15:40:21 27 4
gpt4 key购买 nike

日历有可能从星期一开始吗?我在教程中找到了这个,但我的 JS 知识还不够。我改变了一些值但没有成功。

<script type="text/javascript">
function Calendar(id, year, month) {
var elem = document.getElementById(id)

var mon = month - 1 // (1)
var d = new Date(year, mon)

var table = ['<table><tr>']

// (2) fill first row
// 0 1 2 3 4 5 6
// 29 30 31| 1 2 3 4
for (var i=0; i<d.getDay(); i++) {
table.push('<td></td>')
}

// main body (3)
while(d.getMonth() == mon) {
table.push('<td>'+d.getDate()+'</td>')

if (d.getDay() % 7 == 6) { // (4)
table.push('</tr><tr>')
}

d.setDate(d.getDate()+1)
}

// (5) table tail
for (var i=d.getDay(); i<7; i++) {
table.push('<td></td>')
}

table.push('</tr></table>')

elem.innerHTML = table.join('\n')
}
new Calendar("cal", 2015, 9)
</script>

最佳答案

第一行的列需要向左移动,并将行分隔符设置为“0”(星期日)。

     var firstRow_col = (d.getDay() + 6) % 7;
for (var i=0; i<firstRow_col; i++) {
table.push('<td></td>')
}

...

if (d.getDay() % 7 == 0) { // (4)
table.push('</tr><tr>')
}

编辑:意识到如果表格样式变得可见,尾部也需要清理。

例如:

    if (d.getDay() !== 0)  {
for (var i=0; i < 8 - d.getDay(); i++) {
table.push('<td></td>')
}
}

查看完整代码和演示:

     function Calendar(id, year, month) {
var elem = document.getElementById(id)

var mon = month - 1 // (1)
var d = new Date(year, mon)

var table = ['<table><tr>']

// (2) fill first row
// 0 1 2 3 4 5 6
// 29 30 31| 1 2 3 4
// for (var i=0; i<d.getDay(); i++) {
var firstRow_col = (d.getDay() + 6) % 7;
for (var i = 0; i < firstRow_col; i++) {
table.push('<td></td>')
}

// main body (3)
while (d.getMonth() == mon) {
table.push('<td>' + d.getDate() + '</td>')

// if (d.getDay() % 7 == 6) { // (4)
if (d.getDay() % 7 == 0) { // (4)
table.push('</tr><tr>')
}

d.setDate(d.getDate() + 1)
}

// (5) table tail
for (var i = d.getDay(); i < 7; i++) {
table.push('<td></td>')
}

table.push('</tr></table>')

elem.innerHTML = table.join('\n')
}
new Calendar("cal1", 2015, 1)
new Calendar("cal2", 2015, 2)
new Calendar("cal3", 2015, 3)
new Calendar("cal4", 2015, 4)
new Calendar("cal5", 2015, 5)
new Calendar("cal6", 2015, 6)
new Calendar("cal7", 2015, 7)
new Calendar("cal8", 2015, 8)
new Calendar("cal9", 2015, 9)
new Calendar("cal10", 2015, 10)
new Calendar("cal11", 2015, 11)
new Calendar("cal12", 2015, 12)
Jan <div id="cal1"></div><hr>
Feb <div id="cal2"></div><hr>
Mar <div id="cal3"></div><hr>
Apr <div id="cal4"></div><hr>
May <div id="cal5"></div><hr>
Jun <div id="cal6"></div><hr>
Jul <div id="cal7"></div><hr>
Aug <div id="cal8"></div><hr>
Sep <div id="cal9"></div><hr>
Oct <div id="cal10"></div><hr>
Nov <div id="cal11"></div><hr>
Dec <div id="cal12"></div><hr>

关于javascript - 日历 - 编辑脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32639190/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com