我是Javascript / JQuery的初学者。我想知道如何修改表格单元格高亮显示,如http://jsfiddle.net/Brv6J/所示,并允许以正方形模式进行选择。
例如,考虑A、B、C、D、G、H和I作为表格单元格。沿着从A到E的对角线拖动鼠标应该选择单元格A、B、D和E。
例如,考虑A、B、C、D、G、H和I作为表格单元格。沿着从A到E的对角线拖动鼠标应该选择单元格A、B、D和E。
A B C
D E F
G H I
A B C
D E F
G H I
我之前写过一个用于选择日历的脚本,希望对你有所帮助。
脚本:
$(function () {
$("#table td")
.mousedown(rangeMouseDown)
.mouseup(rangeMouseUp)
.mousemove(rangeMouseMove);
});
var dragStart = 0;
var dragEnd = 0;
var isDragging = false;
function rangeMouseDown(e) {
if (isRightClick(e)) {
return false;
} else {
var allCells = $("#table td");
dragStart = allCells.index($(this));
isDragging = true;
if (typeof e.preventDefault != 'undefined') { e.preventDefault(); }
document.documentElement.onselectstart = function () { return false; };
}
}
function rangeMouseUp(e) {
if (isRightClick(e)) {
return false;
} else {
var allCells = $("#table td");
dragEnd = allCells.index($(this));
isDragging = false;
if (dragEnd != 0) {
selectRange();
}
document.documentElement.onselectstart = function () { return true; };
}
}
function rangeMouseMove(e) {
if (isDragging) {
var allCells = $("#table td");
dragEnd = allCells.index($(this));
selectRange();
}
}
function selectRange() {
$("#table td").removeClass('selected');
if (dragEnd + 1 < dragStart) { // reverse select
$("#table td").slice(dragEnd, dragStart + 1).addClass('selected');
} else {
$("#table td").slice(dragStart, dragEnd + 1).addClass('selected');
}
}
function isRightClick(e) {
if (e.which) {
return (e.which == 3);
} else if (e.button) {
return (e.button == 2);
}
return false;
}
CSS:
#table { border:1px solid #ccc; }
#table td { padding:50px; }
#table td.selected { background-color:#ccc; }
HTML:
<table id="table">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>D</td>
<td>E</td>
<td>F</td>
</tr>
<tr>
<td>G</td>
<td>H</td>
<td>I</td>
</tr>
</table>
我在 http://jsfiddle.net/5VXDt/1/ 创建了一个代码片段。
通过添加单元格的取消选择或选择点击事件,可以改进该脚本。
JQuery Selectable 可能更适合这个要求。
你可以使用 jQuery jquery.ui.draggable.js。
$('td').draggable({
start : function (event, ui) {
// highlighting code
},
stop : function (event, ui) {
//restore the highlighting code
}
});