gpt4 book ai didi

javascript - 使元素在长按时立即可拖动?

转载 作者:行者123 更新时间:2023-12-01 03:37:35 26 4
gpt4 key购买 nike

我有以下代码,可以使元素在长按后可拖动:

$(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')),然后长按时重新启用,但这也不起作用。

这是一个 fiddle ,它演示了我的意思:https://jsfiddle.net/scottbeeson/r5du4p6k/4/

我该怎么做?

最佳答案

添加可拖动元素后,您可以触发元素上的原始事件:

$(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>')
});
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 {
}
<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>

Note that I alse added there .draggable().draggable('enable') to reverse the .draggable('disable') you had on mouseup, to make sure that after you leave the element you will be able to drag it again (after long-press).

关于javascript - 使元素在长按时立即可拖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44145582/

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