使用jQuery,可以通过在mousedown事件上应用.draggable()方法使元素可拖动。然后将其拖动到另一个鼠标按下(并拖动)。是否可以通过单鼠标按下(鼠标向下事件)使元素可拖动并立即开始拖动。
会发生什么?
( 1)按蓝色直角,尝试拖动(元件不可移动);
2)松开直角并再次尝试拖动(元件是可移动的)。
应该发生什么
1)按蓝色直角并拖动->元件是可移动的。
<!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>
发布于 2016-11-07 15:09:17
您需要在小部件初始化之后重新触发mousedown
事件。您可以为此使用.trigger
:
$('#rect').mousedown(function(ev){
console.log(ev.target.id+' pressed');
if ( !$(ev.target).data("ui-draggable") ) {
$(ev.target).draggable();
$(ev.target).trigger(ev);
}
});
请注意可拖放的数据检查:您只需执行一次(否则您将得到一个重新初始化的小部件,并可能得到无限事件触发递归)。
此外,这是默认行为,如果您只是小部件拖放(例如。关于文件准备)
$("#rect").draggable();
一点也不介意mousedown
。这是你应该做的,除非你有很好的理由坚持使用这个事件,这在问题中没有提到。
https://stackoverflow.com/questions/40464357
复制相似问题