实现的功能是新建日程事件需要在左侧日历选定指定日期然后点击导航条的新建按钮,弹出新建图层,选择类型,不同的类型显示出的颜色是不一样的。点击左侧日历时,右侧的日程就会调转到对应的日期,点击右侧的事件会将日历跳转到对应的日期的日视图,新建和删除事件右侧日程会跳转到那天,点击右上的搜索会在日历中搜索内容,右侧的日程会变为一个table显示搜索到的内容。点击table也会将左侧日历跳转到对应日期的日视图,点击返回日程列表就会变回日程显示。
代码如下,我只是自己研究玩的,没有正规培训过,很多代码可能没有按照正规的格式来,写这篇文章主要是为了防止自己以后忘了,很多语法用过再想用却忘了代码咋写了。同时也为给新人一个参考,fullcalendar每个大版本都有不同,很多代码是2和3版本的,网上找了却不会用。
下一个文章会把table替换成calendar3,这个table并没有做完,如果事件很多,找起来会很不方便,没设置滚轮、分页等功能。当时就想用fullcalendar,因为有些关键语法我没弄明白,就做了table的。突然找到了这个关键点怎么用,就转成新日程l了,这样搜索的内容就会变成在日程中显示,而且是按年度或月份显示的。fullcalendar应用(三)我只修改了部分代码,主要代码还是看这篇文章。
calendar.aspx.cs文件如下
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="calendar.aspx.cs" Inherits="TYPE_calendar" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="/js/jquery-3.6.0.js"></script>
<script src="/js/bootstrap.min.js"></script>
<link href="/css/bootstrap.min.css" rel="stylesheet" />
<link href="/js/fullcalendar/main.css" rel="stylesheet" />
<script src="/js/fullcalendar/main.js"></script>
<script src="/js/fullcalendar/zh-cn.js"></script>
<script src="/js/fullcalendar/options.js"></script>
<script src="/js/purple.js"></script>
<link href="/css/purple.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div class="navbar navbar-light bg-light">
<div class="navbar-brand">
<a class="btn btn-primary" href="/Default.aspx">返回首页</a>
<button ID="Button4" class="btn btn-info my-2 my-sm-0" type="button" data-toggle="modal" data-target="#newSchedule">新建</button>
</div>
<div class="form-inline">
<asp:TextBox id="TextBox2" cssclass="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" style="width:400px" runat="server"></asp:TextBox>
<input id="Button2" class="btn btn-outline-success my-2 my-sm-0" type="button" value="查找" />
</div>
</div>
<div style="clear:both">
<div class ="calendar_body">
<div id="calendar" class="calendar_left" ></div>
<div id="calendar2" class="calendar_right"></div>
<div id="findlist" class="calendar_right" style="display:none">
<div><asp:Button ID="Button3" CssClass="btn btn-success" runat="server" Text="返回日程列表" /></div>
<div>
<table id="list_table" style="width: 100%;border:1px solid black" >
<thead>
<tr>
<th>类型</th>
<th>日程内容</th>
<th>开始时间</th>
</tr>
</thead>
</table>
<input name='txtTRLastIndex' type='hidden' id='txtTRLastIndex' value="1" />
</div>
</div>
</div>
</div>
<%-- 以下是隐藏的弹出图层 --%>
<div class="modal fade" id="newSchedule" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">新建日程</h5>
<button id="Button6" type="button" class="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div>
<div class="form-group">
<label class="col-form-label">日程名称:</label>
<input type="text" class="form-control" id="TextBox1" onkeydown="if(event.KeyCode==13) Button1.click()" onmouseover="this.title=this.value">
</div>
<div class="form-group">
<label class="col-form-label">开始时间:</label>
<asp:Label ID="Label1" CssClass="form-control" runat="server" Text="请从日历中选择时间"></asp:Label>
</div>
<div class="form-group">
<label class="col-form-label">结束时间:</label>
<asp:Label ID="Label2" CssClass="form-control" runat="server" Text="请从日历中选择时间"></asp:Label>
</div>
<div class="form-group">
<label class="col-form-label">日程类型:</label>
<select class="custom-select" id="DropDownList1">
<option selected value="0" >请选择...</option>
<option value="Red">会议</option>
<option value="RoyalBlue">培训</option>
<option value="LimeGreen">调研</option>
<option value="MediumOrchid">活动</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<asp:Button ID="Button1" runat="server" cssclass="btn btn-primary" Text="新建" />
<button id="Button7" class="btn btn-secondary" type="Button">取消</button>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
purple.css如下:
#calendar{
max-width: 1000px;
min-width: 700px;
}
#calendar2,
#calendar3
{
max-width: 700px;
min-width: 400px;
}
.calendar_head{
text-align: center;
max-width: 1730px;
margin: 0 auto;
}
.calendar_body{
text-align: center;
max-width: 1700px;
margin: 0 auto ;
}
.calendar_body .calendar_left {
margin: 20px 5px 0;
float: left;
width: 60%;
height: 800px;
}
.calendar_body .calendar_right {
margin: 20px 5px 0;
float: right;
width: 35%;
height: 800px;
overflow:auto;
}
#findlist div:last-child {
margin-top: 25px;
margin-right:10px;
}
#list_table thead tr th,
#list_table thead tr td,
#list_table tbody tr td {
height: 40px;
border-bottom: 1px solid black;
text-align: center;
}
#list_table thead tr th:first-child,
#list_table thead tr td:first-child,
#list_table tbody tr td:first-child {
text-align: center;
width: 50px;
border-bottom: 1px solid black;
border-right: 1px solid black;
}
#list_table thead tr th:nth-child(3),
#list_table thead tr td:nth-child(3),
#list_table tbody tr td:nth-child(3) {
text-align: center;
width: 180px;
border-bottom: 1px solid black;
border-left: 1px solid black;
}
.fc .fc-daygrid-day.fc-day-today {/*修改今天显示的颜色*/
background-color: rgba(255, 0, 0, 0.3);
background-color: var(--fc-today-bg-color, rgba(255, 0, 0 ,0.3));
}
options.js如下:
// calendar
document.addEventListener('DOMContentLoaded', function () {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prevYear,prev,next,nextYear today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
// initialView:'dayGridMonth',//初始视图
initialDate: new Date(),
timeZone: 'locale', //设置时区,默认是locale会有偏差
locale: 'zh-cn', //加载locales-all.js后,选择语言。
navLinks: true, // 可以单击每天/每周名字导航视图
editable: false, //是否可以拖动
dayMaxEvents: true, //当太多的事件允许“更多”链接
businessHours: true,//强调日历中的某些时间段,
weekNumbers: true, //是否在日历中显示第几周,
// weekNumbersWithinDays:true, //在月/基本视图中显示周数的样式
showNonCurrentDates: true,//在月视图中,是否显示上个月和下个月的日期,默认true。
events: {
url: '/ashx/calendar/calendar.ashx',
failure: function () {
document.getElementById('script-warning').style.display = 'block'
}
},
eventReceive: function (info) {
var obj = JSON.stringify(info.event);
alert(obj)
},
selectable: true, //是否可以选择
selectMirror: true,//点击空白月表新建事件,日表可以括时间段
select: function (arg) {
document.getElementById('Label1').innerText = arg.startStr;
document.getElementById('Label2').innerText = arg.endStr;
var data = arg.startStr
document.getElementById('calendar2').style.display = "block";
document.getElementById("findlist").style.display = "none";
calendar2.gotoDate(data);
//下面注释代码是点击日期直接弹出一个输入框,输入title直接建立事件,这里注释掉改成导航栏增加了新建按钮。
//var title = prompt('Event Title:');
arg = JSON.stringify(arg);
alert(arg);
//if (title) {
// var addorder = {
// title: title,
// start: arg.startStr,
// end: arg.endStr,
// //allDay: arg.allDay
// };
// $.ajax({
// url: '/ashx/calendar/insert_calendar.ashx',
// type: 'POST',
// async: false,//在没有返回值之前,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
// data:addorder,
// dataType: 'json',
// success: function (obj) {
// calendar.addEvent({
// title: obj.title,
// start: obj.start,
// end: obj.end,
// //allDay: data.allDay,
// })
// calendar.unselect()
// },
// error: function (XMLHttpRequest, textStatus, errorThrown) {
// alert(errorThrown)
// }
// });
//}
//calendar.unselect()
},
//点击事件触发,
eventClick: function (arg) {
if (confirm('是否要删除此事件')) {
var del_id = JSON.stringify(arg.event.extendedProps.ID)
data1 = { del_id: del_id }
//alert(JSON.stringify(arg)),
$.ajax({
url: '/ashx/calendar/delete_calendar.ashx',
type: 'POST',
//async: false,//在没有返回值之前,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
data: data1,
dataType: 'json',
success: function () {
arg.event.remove(); calendar2.gotoDate(arg.event.startStr); calendar2.refetchEvents();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown)
}
})
}
},
});
calendar.render();
var calendarE2 = document.getElementById('calendar2');
var calendar2 = new FullCalendar.Calendar(calendarE2, {
headerToolbar: {
left: 'prevYear,prev,next,nextYear today',
center: 'title',
right: 'list'
},
height: 'auto',
initialView: 'list',//初始视图
initialDate: new Date(),
timeZone: 'locale', //设置时区,默认是locale会有偏差
locale: 'zh-cn', //加载locales-all.js后,选择语言。
navLinks: false, // 可以单击每天/每周名字导航视图
editable: false, //是否可以拖动
dayMaxEvents: true, //当太多的事件允许“更多”链接
businessHours: true,//强调日历中的某些时间段,
weekNumbers: true, //是否在日历中显示第几周,
// weekNumbersWithinDays:true, //在月/基本视图中显示周数的样式
showNonCurrentDates: true,//在月视图中,是否显示上个月和下个月的日期,默认true。
events: {
url: '/ashx/calendar/calendar.ashx',
failure: function () {
document.getElementById('script-warning').style.display = 'block'
}
},
eventReceive: function (info) {
var obj = JSON.stringify(info.event);
alert(obj)
},
selectable: true, //是否可以选择
selectMirror: false,//点击空白月表新建事件,日表可以括时间段
eventClick: function (arg) {
var data = arg.event.startStr
calendar.changeView("timeGridDay")
calendar.gotoDate(data);
}
});
calendar2.render();
$('#Button1').on('click', function () {
event.preventDefault();
var title = $('#TextBox1').val();
var startStr = $('#Label1').text();
var endStr = $('#Label2').text();
var Schedule = $('#DropDownList1 option:selected').text();
var color = $('#DropDownList1').val();
if (title) {
if (startStr == "请从日历中选择时间") { alert("请从日历中选择时间") }
else {
if (color == 0) { alert("请选择一个日程类型"); }
else {
var addorder = {
title: title,
start: startStr,
end: endStr,
Schedule: Schedule,
color: color
//allDay: arg.allDay
};
console.log(addorder)
$.ajax({
url: '/ashx/calendar/insert_calendar.ashx',
type: 'POST',
//async: false,//在没有返回值之前,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
data: addorder,
dataType: 'json',
success: function (obj) {
newobj = {
title: obj.title,
start: obj.start,
end: obj.end,
Schedule: obj.Schedule,
color: obj.color,
ID: obj.ID
}
console.log("ID:" + obj.ID)
calendar.addEvent(newobj)
calendar2.gotoDate(obj.start)
calendar2.refetchEvents()
calendar.unselect()
new_schedule()
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown)
}
});
}
}
} else {
new_schedule()
}
calendar.unselect()
});
$('#Button2').on('click', function () {
event.preventDefault();
var find = $('#TextBox2').val();
var even = calendar2.getEvents();
var finder = 0;
ClearAllSign();
for (var i = 0; i < even.length; i++) {
if (even[i].title.search(find) != -1) {
AddSignRow(even[i]);
finder += 1;
}
}
if (finder == 0) {
alert("对不起,没有找到关于 “" + find + "” 的相关日程。")
}
else {
document.getElementById('calendar2').style.display = "none";
document.getElementById("findlist").style.display = "block";
}
//var title = even.find(item => item.title =="ddd")//只能找到第一个。
});
$('#Button3').on('click', function () {
event.preventDefault();
document.getElementById('calendar2').style.display = "block";
document.getElementById("findlist").style.display = "none";
});
$('#Button6').on('click', function () { new_schedule()});
$('#Button7').on('click', function () { new_schedule()});
function new_schedule() {
$('#newSchedule').modal('hide');
document.getElementById('TextBox1').value = '';
document.getElementById('Label1').innerText = "请从日历中选择时间";
document.getElementById('Label2').innerText = "请从日历中选择时间";
document.getElementById('DropDownList1').value = "0";
};
//下面的代码都是复制过来的,实际上有些是没用上的。
//js控制table添加删除
function findObj(theObj, theDoc) {
var p, i, foundObj;
if (!theDoc) theDoc = document;
if ((p = theObj.indexOf("?")) > 0 && parent.frames.length)
{ theDoc = parent.frames[theObj.substring(p + 1)].document; theObj = theObj.substring(0, p); } if (!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj]; for (i = 0; !foundObj && i < theDoc.forms.length; i++) foundObj = theDoc.forms[i][theObj]; for (i = 0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) foundObj = findObj(theObj, theDoc.layers[i].document); if (!foundObj && document.getElementById) foundObj = document.getElementById(theObj); return foundObj;
}
//得到行对象
function getRowObj(obj) {
var i = 0;
while (obj.tagName.toLowerCase() != "tr") {
obj = obj.parentNode;
if (obj.tagName.toLowerCase() == "table") return null;
}
return obj;
};
//根据得到的行对象得到所在的行数
function getRowNo(obj) {
var trObj = getRowObj(obj);
var trArr = trObj.parentNode.children;
for (var trNo = 0; trNo < trArr.length; trNo++) {
if (trObj == trObj.parentNode.children[trNo]) {
alert(trNo + 1);
}
}
};
//删除行
function delRow(obj) {
var tr = this.getRowObj(obj);
if (tr != null) {
tr.parentNode.removeChild(tr);
} else {
throw new Error("the given object is not contained by the table");
}
};
//清空列表
function ClearAllSign() {
var signFrame = findObj("list_table", document);
var rowscount = signFrame.rows.length;
//循环删除行,从最后一行往前删除
for (i = rowscount - 1; i > 0; i--) {
signFrame.deleteRow(i);
}
}
//添加table行,复制过来的代码,没改变量名就直接用了。
function AddSignRow(even) { //读取最后一行的行号,存放在txtTRLastIndex文本框中
var txtTRLastIndex = findObj("txtTRLastIndex", document);
var rowID = parseInt(txtTRLastIndex.value);
var signFrame = findObj("list_table", document);
//添加行
var newTR = list_table.insertRow(list_table.rows.length);
newTR.id = "SignItem" + rowID;
//添加列:序号
var newNameiD = newTR.insertCell(0);
//添加列内容
newNameiD.innerHTML = even.extendedProps.Schedule;
//添加列:姓名
var newNameTD = newTR.insertCell(1);
//添加列内容
newNameTD.innerHTML = even.title;
//添加列:电子邮箱
var newEmailTD = newTR.insertCell(2);
//添加列内容
newEmailTD.innerHTML =even.startStr;
//将行号推进下一行
txtTRLastIndex.value = (rowID + 1).toString();
}
$("#list_table thead").on("click", "tr", function () {
var tr = $(this).index();//获得rowIndex
var list_table = findObj("list_table", document);
var data = list_table.rows[tr].cells[2].innerHTML;
calendar.changeView("timeGridDay")
calendar.gotoDate(data);
for (var rowi = 0; rowi < list_table.rows.length; rowi++){
if (rowi == tr) {
list_table.rows[rowi].style.backgroundColor = "#fcfc";
}
else {
list_table.rows[rowi].style.backgroundColor = ""
}
}
});
function cells_color() {
var oColor, td = event.srcElement
console.log(td.id)
if (td.tagName != "TD") //如果事件不是发生在单元格上,退出函数
return
if (event.type == "mouseover") //判断事件类型,决定单元格改变的颜色
oColor = "#dedede"
else oColor = "#ffffff"
//依次捕获的对象为 td.tr.tbody.table.colgroup单元格的上两级对象为表格
cols = td.parentElement.parentElement.parentElement.children[0]
cols.children[td.cellIndex].style.backgroundColor = oColor
}
});
calendar.ashx如下:
<%@ WebHandler Language="C#" Class="calendar" %>
using System;
using System.Web;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using Newtonsoft.Json;
public class calendar : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ace.OLEDB.12.0;User Id=Admin;Data Source=|DataDirectory|data.accdb"); //创建连接对象
conn.Open();
string cal_str = "select * from calendar ";
OleDbCommand cal_Com = new OleDbCommand(cal_str, conn);
OleDbDataAdapter cal_myda = new OleDbDataAdapter();
DataSet caltb = new DataSet();
cal_myda.SelectCommand = cal_Com;
DataTable cal_dt = new DataTable();
cal_myda.Fill(caltb);
cal_dt = caltb.Tables[0];
conn.Close();
string json = JsonConvert.SerializeObject(cal_dt);
context.Response.Write(json);
}
public bool IsReusable {
get {
return false;
}
}
}
insert_calendar.ashx如下:
<%@ WebHandler Language="C#" Class="insert_calendar" %>
using System;
using System.Web;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Data;//data
using System.Data.OleDb;//access
public class insert_calendar : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string title = context.Request["title"];
string start = context.Request["start"];
string end = context.Request["end"];
string Schedule = context.Request["Schedule"];
string color = context.Request["color"];
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ace.OLEDB.12.0;User Id=Admin;Data Source=|DataDirectory|data.accdb"); //创建连接对象
conn.Open();
string insert = "insert into [calendar]([title],[start],[end],[Schedule],[color]) values('" + title + "','" + start + "','" + end +"','" + Schedule +"','" + color + "')";
OleDbCommand P_cmd = new OleDbCommand(insert, conn);//创建命令对象
P_cmd.ExecuteNonQuery();
P_cmd.CommandText = "SELECT @@Identity";
int ID = (int)P_cmd.ExecuteScalar();
conn.Close();
P_cmd.Dispose();
var newObj = new
{
title = title,
start = start,
end = end,
Schedule = Schedule,
color = color,
ID = ID
};
string json = JsonConvert.SerializeObject(newObj);
context.Response.Write(json);
}
public bool IsReusable {
get {
return false;
}
}
}
delete_calendar.ashx如下:
<%@ WebHandler Language="C#" Class="insert_calendar" %>
using System;
using System.Web;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Data;//data
using System.Data.OleDb;//access
public class insert_calendar : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string title = context.Request["title"];
string start = context.Request["start"];
string end = context.Request["end"];
string Schedule = context.Request["Schedule"];
string color = context.Request["color"];
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ace.OLEDB.12.0;User Id=Admin;Data Source=|DataDirectory|data.accdb"); //创建连接对象
conn.Open();
string insert = "insert into [calendar]([title],[start],[end],[Schedule],[color]) values('" + title + "','" + start + "','" + end +"','" + Schedule +"','" + color + "')";
OleDbCommand P_cmd = new OleDbCommand(insert, conn);//创建命令对象
P_cmd.ExecuteNonQuery();
P_cmd.CommandText = "SELECT @@Identity";
int ID = (int)P_cmd.ExecuteScalar();
conn.Close();
P_cmd.Dispose();
var newObj = new
{
title = title,
start = start,
end = end,
Schedule = Schedule,
color = color,
ID = ID
};
string json = JsonConvert.SerializeObject(newObj);
context.Response.Write(json);
}
public bool IsReusable {
get {
return false;
}
}
}