gpt4 book ai didi

html - 允许在 HTML 5 可拖动子元素上选择文本

转载 作者:可可西里 更新时间:2023-11-01 13:45:25 25 4
gpt4 key购买 nike

有一个包含可拖动行的表格,其中每一行都是 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>

最佳答案

我们需要做两件事。

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

  • 另一件事是我们只设置div 上带有content 类的文本可以被选中。我们这样做的原因是已经设置为可拖动的元素,浏览器会在其上添加一个默认规则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>

关于html - 允许在 HTML 5 可拖动子元素上选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44855232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com