效果图
<! DOCTYPE html >
< html lang = " en" > < head> < meta charset = " UTF-8" /> < meta name = " viewport" content = " width=device-width, initial-scale=1.0" /> < title> Document</ title> < style> body { margin : 0; } #box { width : 600px; margin : 50px auto; border : 1px solid blue; } #box header { height : 50px; line-height : 50px; text-align : center; color : #fff; background-color : #17a; padding : 0 10px; } #box header span { cursor : pointer; } #box header span.fl { float : left; } #box header span.fr { float : right; } #box header div { font-size : 30px; } #box table { border-right : 1px solid #ccc; border-bottom : 1px solid #ccc; } #box table th,#box table td { border-left : 1px solid #ccc; border-top : 1px solid #ccc; text-align : center; height : 30px; } </ style> </ head> < body> < div id = " box" > </ div> </ body> < script src = " jquery-3.5.1.min.js" > </ script> < script> $ ( function ( ) { var defaultDate = new Date ( 2021 , 9 ) ; var box = $ ( "#box" ) ; var yearMonthTitleDiv = null ; var prevMonthSpan = null ; var nextMonthSpan = null ; var tBody = null ; var allTd = [ ] ; create ( ) ; showDate ( ) ; function create ( ) { var header = $ ( ` <header><span class="fl">上个月</span><span class="fr">下个月</span><div>2021年10月</div></header> ` ) ; box. append ( header) ; yearMonthTitleDiv = header. find ( "div" ) ; prevMonthSpan = header. find ( ".fl" ) ; nextMonthSpan = header. find ( ".fr" ) ; var table = $ ( ` <table width="100%" cellspacing="0" cellpadding="0"><thead><tr><th class="red">周日</th><th>周一</th><th>周二</th><th>周三</th><th>周四</th><th>周五</th><th>周六</th></tr></thead><tbody></tbody></table> ` ) ; box. append ( table) ; tBody = table. find ( "tbody" ) ; for ( var i = 0 ; i < 6 ; i++ ) { var tr = $ ( "<tr></tr>" ) ; for ( var k = 0 ; k < 7 ; k++ ) { var td = $ ( "<td></td>" ) ; tr. append ( td) ; allTd. push ( td) ; } tBody. append ( tr) ; } } function showDate ( ) { var year = defaultDate. getFullYear ( ) ; var month = defaultDate. getMonth ( ) + 1 ; yearMonthTitleDiv. text ( year + "年" + month + "月" ) ; var week = new Date ( year, month - 1 , 1 ) . getDay ( ) ; var days = new Date ( year, month, 0 ) . getDate ( ) ; var n = 1 ; for ( let i = 0 ; i < allTd. length; i++ ) { allTd[ i] . empty ( ) ; if ( i >= week && n <= days) { allTd[ i] . text ( n) ; n++ ; } } if ( allTd[ 28 ] . text ( ) === '' ) { allTd[ 28 ] . parent ( ) . hide ( ) ; allTd[ 35 ] . parent ( ) . hide ( ) ; } else if ( allTd[ 35 ] . text ( ) === '' ) { allTd[ 35 ] . parent ( ) . hide ( ) ; } else { allTd[ 28 ] . parent ( ) . show ( ) ; allTd[ 35 ] . parent ( ) . show ( ) ; } } $ ( "#box span" ) . click ( function ( ) { var year = defaultDate. getFullYear ( ) ; var month = defaultDate. getMonth ( ) ; if ( $ ( this ) . index ( ) == 0 ) { month-- ; } else { month++ ; } defaultDate = new Date ( year, month) ; showDate ( ) ; } ) ; } ) ; </ script>
</ html>