8

有一个每行都是可拖动行的表格,draggable=true用户如何仍然能够从列中选择文本?

<table>
 <thead>..</thead>
 <tbody>
  ..
  <tr draggable="true">
   <td>..</td>
   <td>Cool text but you can't select me</td>
   <td>..</td>
  </tr>
  ..
</tbody>
</table>

另一个简单的例子(https://codepen.io/anon/pen/qjoBXV

div {
  padding: 20px;
  margin: 20px;
  background: #eee;
}

.all-copy p {  
  -webkit-user-select: all;  /* Chrome all / Safari all */
  -moz-user-select: all;     /* Firefox all */
  -ms-user-select: all;      /* IE 10+ */
  user-select: all;          /* Likely future */   
}    
<div class="all-copy" draggable="true">
      <p>Select me as text</p>
    </div>
4

2 回答 2

7

我们需要做两件事。

  • 一件事是限制拖动事件仅在指定区域触发,例如拖动手柄。

  • 另一件事是我们只设置了div上的text with content class可以选择。我们这样做的原因是已经设置为可拖动的元素,浏览器会在其上添加默认规则user-select: none

const itemEl = document.querySelector('.item');
const handleEl = document.querySelector('.handle');

let mouseDownEl;

itemEl.onmousedown = function(evt) {
  mouseDownEl = evt.target;
}

itemEl.ondragstart = function(evt) {
  // only the handle div can be picked up to trigger the drag event
  if (mouseDownEl.matches('.handle')) {
    // ...code
  } else {
    evt.preventDefault();
  }
}
.item {
  width: 70px;
  border: 1px solid black;
  text-align: center;
}

.content {
  border-top: 1px solid gray;
  user-select: text;
}
<div class="item" draggable="true">
  <div class='handle'>handle</div>
  <div class='content'>content</div>
</div>

于 2018-07-06T20:23:34.567 回答
2

我可以看到这项工作的唯一方法是实际检查哪个元素触发了事件

if (e.target === this) {...}

堆栈片段

(function (elem2drag) {
  var x_pos = 0, y_pos = 0, x_elem = 0, y_elem = 0;  
  
  document.querySelector('#draggable').addEventListener('mousemove', function(e) {
    x_pos = e.pageX;
    y_pos = e.pageY;
    if (elem2drag !== null) {
        elem2drag.style.left = (x_pos - x_elem) + 'px';
        elem2drag.style.top = (y_pos - y_elem) + 'px';
    }  
  })

  document.querySelector('#draggable').addEventListener('mousedown', function(e) {
    if (e.target === this) {
      elem2drag = this;
      x_elem = x_pos - elem2drag.offsetLeft;
      y_elem = y_pos - elem2drag.offsetTop;
      return false;
    }  
  })
  
  document.querySelector('#draggable').addEventListener('mouseup', function(e) {
    elem2drag = null;
  })
})(null);
#draggable {
  display: inline-block;
  background: lightgray;
  padding:15px;
  cursor:move;
  position:relative;
}
span {
  background: white;
  line-height: 25px;
  cursor:auto;  
}
<div id="draggable">
  <span>Select me as text will work<br>when the mouse is over the text</span>
</div>


由于Firefox 有问题draggable="true",我使用了不同的拖动方法。

于 2017-07-01T11:30:56.070 回答