我有以下代码,在长按后使元素可拖动:
$(document).on('touchstart mousedown','.menu-item', function () {
console.log('mousedown');
var self = this;
t = setTimeout(function () {
$(self).addClass('draggable');
console.log('draggable');
$(self).draggable();
}, 800);
});
技术上可行,但你必须放松鼠标然后点击拖动。我希望这是无缝的。我尝试在DOM加载时将它们全部拖动,然后禁用它们(.draggable('disable')
),然后在长按时重新启用,但这也不起作用。
这是一个演示我的意思的小提琴:https://jsfiddle.net/scottbeeson/r5du4p6k/4/
我该怎么做?
答案 0 :(得分:2)
添加draggable后,您可以在元素上触发原始事件:
$(self).draggable().addClass('draggable');
$(self).trigger(event)
这是一个有效的例子:
var t;
$(document).on('mousedown','.menu-item', function (event) {
var self = this;
if ($(self).hasClass('draggable')) {
return;
}
t = setTimeout(function () {
$(self).draggable().draggable('enable').addClass('draggable');
console.log('start drag');
$(self).trigger(event)
}, 800);
});
$(document).on("mouseup", function () {
clearTimeout(t);
$('.draggable').removeClass('draggable').draggable( 'disable' )
});
$(function() {
$('#container').append('<div class="menu-item">1</div>')
$('#container').append('<div class="menu-item">2</div>')
$('#container').append('<div class="menu-item">3</div>')
$('#container').append('<div class="menu-item">4</div>')
$('#container').append('<div class="menu-item">5</div>')
});
&#13;
body {
background: lightgray;
}
.menu-item {
display: inline-block;
width: 40px; height: 40px;
background-color: white;
margin: 5px;
text-align: center;
line-height: 40px;
cursor: pointer;
user-select: none;
transform: scale(1);
}
.draggable {
background-color: yellow;
transform: scale(1.2);
}
#log {
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div id='container'>
</div>
<div id='log'>
</div>
&#13;
请注意,我还添加了
.draggable().draggable('enable')
来反转你在mouseup上的.draggable('disable')
,以确保在你离开元素之后你可以再次拖动它(在长按之后)