利用Javascript开发一个二维周视图日历(6)
点击事件和范围选择
此控件不仅用于结果展示,还要可用于点击进行添加,需要处理其点击事件,但是由于要展示内容,内容是覆盖在分类和日期构成的网格之上的,用户的点击是点击不到网格元素的,必须要根据点击的位置进行计算来获取所点击的日期和所在分类。
同时,由于展示的部件都是时间范围的,因此点击返回某天和某个分类是不够的,还需要能够支持鼠标按下拖动再松开,来直接选的一段时间。
考虑到以上需求,点击事件不能直接使用 click 来实现,考虑使用 mousedown 和 mouseup 来处理点击事件,同时需要在 mousemove 中实时给出用户响应。
{
_initEvent: function () {
var me = this;
// 点击的行索引
var row,
// 开始列索引
columnStart,
// 结束列索引
columnEnd,
// 是否在按下、移动、松开的click中
isDurringClick = false,
// 是否移动过 用于处理按下没有移动直接松开的过程
isMoveing = false,
$columns,
// 网格左侧宽度
gridLeft,
// 每列的宽度
columnWidth
jQuery(this.el)
// 按下鼠标 记录分类和开始列
.on('mousedown.weekcalendar', '.ep-weekcalendar-content-row', function (e) {
isDurringClick = true;
gridLeft = jQuery(me._gridEl).offset().left;
columnWidth = jQuery(me._gridEl).width() / 7;
jQuery(me._gridEl).find('.ep-weekcalendar-grid-item').removeClass(me._selectedCls);
row = this.getAttribute('data-i');
$columns = jQuery(me._gridEl).find('.ep-weekcalendar-grid-row').eq(row).children();
columnStart = (e.pageX - gridLeft) / columnWidth >> 0;
});
// 移动和松开 松开鼠标 记录结束列 触发点击事件
// 不能直接绑定在日期容器上 否则鼠标移出日历后,松开鼠标,实际点击已经结束,但是日历上处理不到。
jQuery('body')
// 点击移动过程中 实时响应选中状态
.on('mousemove.weekcalendar', function (e) {
if (!isDurringClick) {
return;
}
isMoveing = true;
// 当前列索引
var currColumn;
// mousemoveTimer = setTimeout(function () {
currColumn = (e.pageX - gridLeft) / columnWidth >> 0;
// 修正溢出
currColumn = currColumn > 6 ? 6 : currColumn;
currColumn = currColumn < 0 ? 0 : currColumn;
$columns.removeClass(me._selectedCls);
// 起止依次选中
var start = Math.min(columnStart, currColumn),
end = Math.max(columnStart, currColumn);
do {
$columns.eq(start).addClass(me._selectedCls);
} while (++start <= end);
})
// 鼠标松开
.on('mouseup.weekcalendar', function (e) {
if (!isDurringClick) {
return;
}
var startIndex = -1,
endIndex = -1;
columnEnd = (e.pageX - gridLeft) / columnWidth >> 0;
columnEnd = columnEnd > 6 ? 6 : columnEnd;
// 没有移动过时
if (!isMoveing) {
startIndex = endIndex = columnEnd;
// 直接down up 没有move的过程则只会有一个选中的,直接以结束的作为处理即可
$columns.eq(columnEnd).addClass(me._selectedCls)
.siblings().removeClass(me._selectedCls);
} else {
startIndex = Math.min(columnStart, columnEnd);
endIndex = Math.max(columnStart, columnEnd);
}
// 触发点击事件
me.fire('cellClick', {
// 分类id
categoryId: me._categoryIndexs[row],
// 时间1
startDate: me._dateRecords[startIndex].format('YYYY-MM-DD'),
// 日期2
endDate: me._dateRecords[endIndex].format('YYYY-MM-DD'),
// 行索引
rowIndex: row,
// 列范围
columnIndexs: (function (i, j) {
var arr = [];
while (i <= j) {
arr.push(i++);
}
return arr;
}(startIndex, endIndex))
});
row = columnStart = columnEnd = isMoveing = isDurringClick = false;
});
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
