jquery-ui:在鼠标按下时立即可拖动 [英] jquery-ui: immediate draggable on mousedown
问题描述
使用jQuery-UI,可以通过在 mousedown 事件上应用.draggable()方法来使元素可拖动。然后将其拖动到另一个鼠标上(并拖动)。
是否可以使元素可拖动并通过单击鼠标立即开始拖动(鼠标移下事件)。
Working with jQuery-UI, it is possible to make an element draggable by applying .draggable() method on mousedown event. And then drag it on another mouse press (and drag). Is it possible to make element draggable and start dragging immediately by single mouse press (mousedown event).
会发生什么情况:
1)按蓝色rect并尝试拖动(元素不可移动);
1) press blue rect and try to drag (element not movable);
2)取消按rect并尝试再次拖动(元素是可移动的)。
2) unpress rect and try to drag again (element is movable).
会发生什么情况:
1)按蓝色矩形并将其拖动->元素可移动。
1) press blue rect and drag it --> element is movable.
<!DOCTYPE html>
<html>
<head>
<title>draggable() on press</title>
<meta charset='UTF-8'/>
<style>#rect{ border: 1px dotted blue; width:100px; height:100px; background-color: lightblue;}</style>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'></script>
<script>
$(document).ready(function(){
console.log('document is ready');
$('#rect').mousedown(function(ev){
console.log(ev.target.id+' pressed');
$(ev.target).draggable();
// $(this).draggable(); // Works the same.
});
});
</script>
</head>
<body>
<div id='rect'></div>
</body>
</html>
推荐答案
您需要重新触发<$ c $小部件初始化后的c> mousedown 事件。您可以为此使用 .trigger
:
You need to re-trigger the mousedown
event after the widget initialization. You can use .trigger
for this:
$('#rect').mousedown(function(ev){
console.log(ev.target.id+' pressed');
if ( !$(ev.target).data("ui-draggable") ) {
$(ev.target).draggable();
$(ev.target).trigger(ev);
}
});
请注意可拖动数据检查:您只需要执行一次(否则您将获得一次-初始化的窗口小部件,并且可能是无限事件触发递归)
Note the draggable data check: you have to only do this ONCE (or you'd get a re-initialised widget and possibly infinite event trigger recursion)
此外,如果您只是可拖动的窗口小部件(例如,在准备文档时),则这是默认行为
Also, this is the default behaviour if you only just the widget draggable (eg. on document-ready)
$("#rect").draggable();
完全不用为 mousedown
而烦恼。这是您应该执行的操作,除非您有充分的理由坚持使用该事件(问题中未提及)
and not bother with mousedown
at all. This is what you should do unless you have very good reason to insist on using the event, which isn't mentioned in the question
小提琴: https://jsfiddle.net/9ame9ege/
这篇关于jquery-ui:在鼠标按下时立即可拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!