【发布时间】:2023-04-15 00:25:01
【问题描述】:
我是一名学生,刚接触编程,想通过尝试学习 Javascript。我正在做一个练习,需要我在鼠标拖动时突出显示表格单元格。我让它工作,但我在弄清楚如何通过拖动任何方向(不仅仅是从 X 到 Y 方向)来突出显示单元格时遇到问题。下面的代码显示了它是如何从 X 到 Y 方向工作的;当用户将鼠标从 Y 方向拖动到 X 方向时,我希望它做同样的事情。
例如,将A, B, C, D, G, H 和I 视为表格单元格。
A B C
D E F
G H I
沿对角线从 A 到 E 拖动鼠标选择单元格 A,B,D & E。我希望在鼠标从 I 拖动到 E 时选择 I、H、F、E。
这里是工作代码:
$(function () {
var isMouseDown = false,
isHighlighted;
var mouseDownRowX = 0;
var mouseDownRowY = 0;
$("#assayPlateTable2 td.dragShadow")
.click(function () {
$("#assayPlateTable2 td").each(function () {
var currClass = $(this).attr('class');
if(currClass == 'dragShadow') {
$(this).css('backgroundColor', 'none');
}
});
var currClass = $(this).attr('class');
if(currClass == 'dragShadow') {
$(this).css('backgroundColor', '#dff0de');
}
currRow = $(this).parent().parent().children().index($(this).parent());
})
.mousedown(function () {
isMouseDown = true;
mouseDownRowX = $(this).parent().parent().children().index($(this).parent());
mouseDownRowY = $(this).parent().children().index($(this));
return false; // prevent text selection
})
.mouseover(function () {
//alert('mouse over' + isMouseDown);
if (isMouseDown) {
currRow = $(this).parent().parent().children().index($(this).parent());
currCol = $(this).parent().children().index($(this));
//var currRow = 1;
//var currCol = 1;
$("#assayPlateTable2 td").each(function () {
_mouseDownRowX = $(this).parent().parent().children().index($(this).parent());
_mouseDownRowY = $(this).parent().children().index($(this));
if(_mouseDownRowX >=
mouseDownRowX && _mouseDownRowX <= currRow && _mouseDownRowY
>= mouseDownRowY && _mouseDownRowY <= currCol) {
var currClass = $(this).attr('class');
if(currClass == 'dragShadow') {
$(this).css('backgroundColor', '#dff0de');
}
//alert("setting==>" + currRow + "," + currCol);
} else {
var currClass = $(this).attr('class');
if(currClass == 'dragShadow') {
$(this).css('backgroundColor', 'none');
}
}
});
for(var i = mouseDownRowX; i < _mouseDownRowX; i++) {
for(var j = mouseDownRowY; j < _mouseDownRowY; j++) {
}
}
//$(this).parent().toggleClass("highlighted", isHighlighted);
//$(this).parent().css('backgroundColor', '#dff0de');
}
})
.bind("selectstart", function () {
return false;
})
$(document)
.mouseup(function () {
isMouseDown = false;
});
});
</script>
HTML:
<table cellpadding="0" cellspacing="0" id="assayPlateTable2">
<tr>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
</tr>
<tr>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
</tr>
<tr>...</tr> and so on
</table>
【问题讨论】:
标签: javascript jquery html-table cell highlight