1

在此处输入图像描述

我想将鼠标拖到单元格上,然后选择单元格下的任何内容。只有它下面的单元格被选中。如果用户以之字形方式移动鼠标,则不会发生选择。

4

1 回答 1

0

这是我在 Chrome 上测试的解决方案。我不确定您是否希望在开始拖动时选择第一个方格,因此我将其保留为未选择,以便在开始之字形之前不选择它。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
td{padding: 100px;}
.selected{background-color: #f55;}
.deselected{background-color: #faa;}
</style>
<script>
var dragging = false
var reference
addEventListener("load", function(){
  var squares = document.querySelectorAll("td")
  for(var i = 0; i < squares.length; ++i){
    squares[i].draggable = true
    squares[i].className = "deselected"
    squares[i].addEventListener("dragstart", function(){
      reference = this
      dragging = true
    })
    squares[i].addEventListener("drop", function(){dragging = false})
    squares[i].addEventListener("dragenter", toggle)
  }
})
function toggle(){
  if(!dragging) return
  if(this == reference) return
  var rect = reference.getBoundingClientRect()
  if(this.getBoundingClientRect().top < rect.top){
    dragging = false
    return
  }
  if(this.getBoundingClientRect().left != rect.left){
    dragging = false
    return
  }
  if(this.className == "selected"){
    this.className = "deselected"
  }
  else{
    this.className = "selected"
  }
}
</script>
</head>
<body>
<table>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
</table>
</body>
</html>
于 2015-05-24T13:49:55.893 回答