在Chrome浏览器中,Touchmove事件未在“此”对象上获取正确的元素

时间:2019-02-07 11:49:54

标签: javascript jquery google-chrome drag touchmove

我正在使用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>

0 个答案:

没有答案