我正在使用touchmove
事件在应用程序中的表上进行拖动选择。当它在计算机上运行时,它会通过mouseover
事件正确选择。
但是,在iPad上,它什么也不会选择。当我对此进行更深入的研究时,发现$(this)
并未更新当前的touch move元素,而是指向其开始的元素。
var table = $("#table");
var isMouseDown = false;
var startRowIndex = null;
var startCellIndex = null;
var de = 1;
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").on("mousedown touchstart", function(e) {
isMouseDown = true;
var cell = $(this);
table.find(".selected").removeClass("selected"); // deselect everything
cell.addClass("selected");
startCellIndex = cell.index();
startRowIndex = cell.parent().index();
return false; // prevent text selection
}).on("mouseover touchmove", function() {
if (!isMouseDown) return;
table.find(".selected").removeClass("selected");
selectTo($(this));
})
.bind("selectstart", function() {
return false;
});
$(document).on("mouseup touchend ", function() {
isMouseDown = false;
});
table td {
border: 1px solid #999;
width: 80px;
height: 40px;
margin: 10px;
}
td.selected {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
</table>