javascript 如何在 jQuery 可拖动 div 上选择文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11075068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you make text selectable on a jQuery draggable div?
提问by SamFisher83
I made a div draggable using jQuery. However, there is some text in that box, and I would still like to be able to copy and paste the text, but when I make an item draggable well when I click on the box it starts to move the box?
我使用 jQuery 制作了一个可拖动的 div。但是,该框中有一些文本,我仍然希望能够复制和粘贴文本,但是当我单击该框时使项目可以很好地拖动时,它会开始移动该框?
回答by Nikolay Lapitskiy
Use the cancel
optionwhen making the element draggable.
使元素可拖动时使用该cancel
选项。
Prevents dragging from starting on specified elements.
防止从指定元素开始拖动。
$('.selector').draggable({ cancel: '.text' });
回答by ldiqual
It doesn't make sense to allow dragging AND selecting text on the same element. However, if you keep thinking it's necessary, two things come to my mind:
允许在同一元素上拖动和选择文本是没有意义的。但是,如果您一直认为这是必要的,我会想到两件事:
Solution 1:
解决方案1:
You can add a "handler" that will be the only child receiving the mouse down/up events to drag the div. For instance:
您可以添加一个“处理程序”,它将是唯一接收鼠标向下/向上事件以拖动 div 的子项。例如:
<div id="draggable">
<div class="handler"></div>
<div class="text">This is a selectable text</div>
</div>
And in your JavaScript code:
在你的 JavaScript 代码中:
var draggableDiv = $('#draggable');
draggableDiv.draggable({
handle: $('.text', draggableDiv)
});
Solution 2:
解决方案2:
You can disable the draggable thing when a user try to select text:
当用户尝试选择文本时,您可以禁用可拖动的东西:
<div id="draggable">
<div class="text">This is a text</div>
</div>
And in your JavaScript code:
在你的 JavaScript 代码中:
var draggableDiv = $('#draggable').draggable();
$('.text', draggableDiv).mousedown(function(ev) {
draggableDiv.draggable('disable');
}).mouseup(function(ev) {
draggableDiv.draggable('enable');
});
When someone tries to select something in .text
, the draggable process is disabled.
当有人尝试在 中选择某些内容时.text
,可拖动过程将被禁用。
The first solution is the proper one.
第一个解决方案是正确的。