我想在单元格上拖动鼠标,选择单元格下的任何内容。只有它的单元格被选中。如果用户移动鼠标之字形方式,则不会发生任何选择。我怎么能这样做。
$(".csstablelisttd").live('mousedown', function (e){
//This line gets the index of the first clicked row.
lastRow = $(this).closest("tr")[0].rowIndex;
rowIndex = $(this).closest("tr").index();
colIndex = $(e.target).closest('td').index();
$(".csstdhighlight").removeClass("csstdhighlight");
$('#tableAppointment tr').eq(rowIndex).find('td').eq(colIndex).addClass('csstdhighlight');
flag = true;
return false;
});
document.onmousemove = function () { return false; };
$(".csstablelisttd").live('mouseenter', function (e){
// Compares with the last and next row index.
currentRow = $(this).closest("tr")[0].rowIndex;
currentColoumn = $(e.target).closest('td').index();
if (lastRow == currentRow || lastRow == currentRow - 1 || lastRow == currentRow + 1){
lastRow = $(this).closest("tr")[0].rowIndex;
}else{
return;
}
if (flag){
$('#tableAppointment tr').eq(currentRow ).find('td').eq(currentColoumn ).addClass('csstdhighlight');
e.preventDefault();
flag = false;
}
});
答案 0 :(得分:1)
在这里:http://jsfiddle.net/EAETy/。我已经收紧了逻辑/代码。希望这有助于和/或给你一些建议。
var currentColumn,
currentRow,
flag = false,
maxSlots = 3
$table = $("#tableAppointment");
document.onmouseup = function () { flag = false; };
//helper function instead of alerts
var flashColor = function(element){
element.addClass('red');
setTimeout(function(){
element.removeClass('red');
},300);
};
$table.on('mousedown', 'td', function(e) {
//store jquery this reference since we use it multiple times
var $td = $(this);
//set current row and column
currentColumn = $td.index();
currentRow = $td.parent().index();
//are there unclickable columns and rows?
if (currentColumn < 2 || currentRow < 1) {
flashColor($td);
return false;
}
//remove old highlight if any
//(find it faster by adding the $table[0] context)
$(".csstdhighlight",$table[0]).removeClass('csstdhighlight');
//add new highlight
$td.addClass('csstdhighlight');
//set mousedown flag
flag = true;
//prevent text highlighting while dragging
return false;
});
$table.on('mouseenter', 'td', function(e) {
//no need to do stuff here if user hasn't moused down
if (!flag) return false;
//get row and column for this mouseenter event
var $td = $(this),
$row = $td.parent(),
rowIndex = $row.index(),
colIndex = $td.index();
//don't let mouse cross columns
//or skip rows (from too fast mouse movement)
if(colIndex !== currentColumn
|| !$row[rowIndex>currentRow ? "prev" : "next"]().children('.csstdhighlight').length) {
flag = false;
return false;
}
//add new highlight
$td.addClass('csstdhighlight');
//stop after 3 highlights
if ($(".csstdhighlight", $table[0]).length >= maxSlots) {
flashColor($(".csstdhighlight", $table[0]));
flag = false;
}
});