【发布时间】:2021-09-06 02:38:18
【问题描述】:
我需要选择和取消选择表格单元格范围的功能。附加的代码运行良好,但它使用 JQuery,而我的项目的其余部分使用纯 JavaScript。 onmousedown、onmouseover 和 onmouseup 是这段代码中使用的三个鼠标事件。
我试图将此 JQuery 代码转换为纯 JavaScript,但未能成功。如果您能在这方面帮助我,我将不胜感激。
谢谢!
var table = $("#table");
var isMouseDown = false;
var startRowIndex = null;
var startCellIndex = null;
function selectTo(cell) {
var row = cell.parent();
var cellIndex = cell.index();
var rowIndex = row.index();
var rowStart, rowEnd, cellStart, cellEnd;
if (rowIndex < startRowIndex) {
rowStart = rowIndex;
rowEnd = startRowIndex;
} else {
rowStart = startRowIndex;
rowEnd = rowIndex;
}
if (cellIndex < startCellIndex) {
cellStart = cellIndex;
cellEnd = startCellIndex;
} else {
cellStart = startCellIndex;
cellEnd = cellIndex;
}
for (var i = rowStart; i <= rowEnd; i++) {
var rowCells = table.find("tr").eq(i).find("td");
for (var j = cellStart; j <= cellEnd; j++) {
rowCells.eq(j).addClass("selected");
}
}
}
table.find("td").mousedown(function (e) {
isMouseDown = true;
var cell = $(this);
table.find(".selected").removeClass("selected"); // deselect everything
if (e.shiftKey) {
selectTo(cell);
} else {
cell.addClass("selected");
startCellIndex = cell.index();
startRowIndex = cell.parent().index();
}
return false; // prevent text selection
})
.mouseover(function () {
if (!isMouseDown) return;
table.find(".selected").removeClass("selected");
selectTo($(this));
})
.bind("selectstart", function () {
return false;
});
$(document).mouseup(function () {
isMouseDown = false;
});
table td {
border: 1px solid #999;
width: 40px;
height: 15px;
margin: 10px;
}
td.selected {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
Click and drag mouse or use shift key to select cells.
<table id="table">
<tr>
<td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
</tr>
</table>
</body>
【问题讨论】:
标签: javascript jquery html-table