JavaScript 和 ASP.NET 中的时间选择器





4.00/5 (7投票s)
一个 web 应用程序,允许用户在 ASP.NET 页面中选择时间段。
引言
这是之前在 CodeProject 上编写的 WinForms 时间选择器控件的 web 实现。此实现允许用户直接从 web 应用程序中选择一天中的不同时间段。
背景
为了实现时间段选择器,我需要找到一个客户端脚本库,该库允许我在 web 浏览器上绘制线条和突出显示矩形。在 Google 上搜索了一番后,我找到了这个 绘图库,它使我能够绘制初始的静态日历。
绘制日历的工作量占 50%,另外 50% 的工作是允许用户在鼠标按下事件上突出显示日历单元格,并在类似于 Paint 等任何图形应用程序的选择框的鼠标抬起事件上停止突出显示它们。
使用代码
基本思想是定义一个 div
区域,在该区域中进行绘图,然后将该区域内的鼠标事件连接到相应的绘图函数。在我的 ASPX 文件中,我定义了一个 id="MyCanvas"
的区域,如下所示
<div id="myCanvas" style="position:relative;height:230px;width:550px;"
onmousedown="StartSelection(event, this)"
onmousemove="HighlightCell(event, this)"
onmouseup="EndSelection(event, this)"
onmouseout="MouseExited(event, this)"></div>
在上面的 div
中,我将鼠标按下事件连接到 StartSelection
,将鼠标移动事件连接到 HighlightCell
,将鼠标抬起事件连接到 EndSelection
,最后将鼠标移出事件连接到 MouseExited
。
StartSelection
标记单元格突出显示的开始,然后由 HighlightCell
检查以确定鼠标下的单元格是否应作为正在进行的选区的一部分突出显示。 EndSelection
只是关闭选择标志,这样来自鼠标移动事件的后续对 HiglightCell
的调用将不会导致单元格选择。
最后,当鼠标简单地退出画布区域时,需要 OnMouseExited
来结束选择。
关注点
最初,需要定义一些全局变量
var jg = new jsGraphics("myCanvas");
var xTextCellOffset=20;
var yTextCellOffset=10;
var daysCellWidth=150;
var daysCellHeight=30;
var timeChartGridWidth=400;
var timeChartGridHeight=daysCellHeight*7;
var cellWidth=timeChartGridWidth/24; // half an hour increments
var cellHeight=daysCellHeight;
var selectedCells=new Array();
除了上述绘图机制之外,还提供了一些静态函数来绘制初始日历。我编写了一些基本的绘图例程,这些例程建立在上面提到的 wz_jsgraphics 绘图库之上
DrawGrid
此函数允许您从像素 (x, y) 点开始绘制网格,并指定一定的宽度和高度,同时指定行数和列数
function DrawGrid(x, y, width, height, numberOfRows, numberOfColumns)
{
for(row=0; row<=numberOfRows; row++)
{
var rowInPixles=y+row*height/numberOfRows;
jg.drawLine(x, rowInPixles, x+width, rowInPixles);
}
for(col=0; col<=numberOfColumns; col++)
{
var colInPixles=x+col*width/numberOfColumns;
jg.drawLine(colInPixles, y, colInPixles, y+height);
}
}
DrawCalendar
函数 DrawCalendar
采用日历类型(伊斯兰或基督教),并绘制日期轴、日期时间轴(对于伊斯兰历,星期五是第一天,对于基督教历,星期日是第一天)以及划分为 24 小时的每小时网格
function DrawCalendar(type)
{
// Reset Selection Memory
selectedCells=new Array();
// Highlight the active Calendar type
if(type==1)
{
document.getElementById( "Islamic" ).style.color="Black";
document.getElementById( "Christian" ).style.color="Gray";
}
else if(type==2)
{
document.getElementById( "Islamic" ).style.color="Gray";
document.getElementById( "Christian" ).style.color="Black";
}
jg.clear();
DrawDaysAxies(type);
DrawTimeAxis();
DrawTimeChartGrid();
jg.paint();
}
就这些了!