jQuery 드래그 앤 드롭으로 클릭 이벤트 방지
페이지에 jQuery로 드래그 할 수있는 요소가 있습니다. 이러한 요소에 다른 페이지 (예 : 일반 링크)로 이동하는 클릭 이벤트가 있습니까?
드래그 앤 드롭 상태가 아닌 클릭을 허용하면서 이러한 요소를 놓을 때 클릭이 발생하지 않도록하는 가장 좋은 방법은 무엇입니까?
정렬 가능한 요소 에이 문제가 있지만 일반적인 드래그 앤 드롭에 대한 솔루션을 갖는 것이 좋다고 생각합니다.
나는 스스로 문제를 해결했다. 그 후 Scriptaculous 에 대해 동일한 솔루션 이 존재 한다는 것을 발견 했지만 누군가가 그것을 달성하는 더 좋은 방법이있을 수 있습니다.
나를 위해 잘 작동하고 시간 초과가 필요하지 않은 솔루션 : (예, 약간 현학적입니다 ;-)
드래그가 시작될 때 요소에 마커 클래스를 추가합니다 (예 : 'noclick'). 요소가 드롭되면 클릭 이벤트가 트리거됩니다. 더 정확하게는 드래그가 끝나면 실제로 유효한 타겟에 드롭 할 필요가 없습니다. 클릭 핸들러에서 마커 클래스가 있으면 제거합니다. 그렇지 않으면 클릭이 정상적으로 처리됩니다.
$('your selector').draggable({
start: function(event, ui) {
$(this).addClass('noclick');
}
});
$('your selector').click(function(event) {
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
}
else {
// actual click event code
}
});
해결책은 드래그 시작시 클릭이 전파되는 것을 방지하는 클릭 핸들러를 추가하는 것입니다. 그리고 드롭이 수행 된 후 해당 핸들러를 제거하십시오. 클릭 방지가 작동하려면 마지막 작업이 약간 지연되어야합니다.
정렬 가능한 솔루션 :
...
.sortable({
...
start: function(event, ui) {
ui.item.bind("click.prevent",
function(event) { event.preventDefault(); });
},
stop: function(event, ui) {
setTimeout(function(){ui.item.unbind("click.prevent");}, 300);
}
...
})
드래그 가능한 솔루션 :
...
.draggable({
...
start: function(event, ui) {
ui.helper.bind("click.prevent",
function(event) { event.preventDefault(); });
},
stop: function(event, ui) {
setTimeout(function(){ui.helper.unbind("click.prevent");}, 300);
}
...
})
나는 같은 문제가 있었고 여러 가지 접근 방식을 시도했지만 아무도 나를 위해 일하지 않았습니다.
해결책 1
$('.item').click(function(e)
{
if ( $(this).is('.ui-draggable-dragging') ) return false;
});
나를 위해 아무것도하지 않습니다. 드래그가 완료된 후 항목이 클릭됩니다.
솔루션 2 (Tom de Boer 작성)
$('.item').draggable(
{
stop: function(event, ui)
{
$( event.originalEvent.target).one('click', function(e){ e.stopImmediatePropagation(); } );
}
});
이것은 잘 작동하지만 한 가지 경우에 실패합니다.
var body = $('body')[0];
req = body.requestFullScreen || body.webkitRequestFullScreen || body.mozRequestFullScreen;
req.call(body);
솔루션 3 (Sasha Yanovets 제작)
$('.item').draggable({
start: function(event, ui) {
ui.helper.bind("click.prevent",
function(event) { event.preventDefault(); });
},
stop: function(event, ui) {
setTimeout(function(){ui.helper.unbind("click.prevent");}, 300);
}
})
이것은 나를 위해 작동하지 않습니다.
솔루션 4- 잘 작동하는 유일한 솔루션
$('.item').draggable(
{
});
$('.item').click(function(e)
{
});
네, 그게 다입니다. 올바른 순서가 트릭을 수행합니다. 먼저 draggable ()을 바인딩 한 다음 click () 이벤트를 바인딩해야합니다. click () 이벤트에 전체 화면 토글 코드를 입력해도 드래그 할 때 전체 화면으로 이동하지 않았습니다. 나 한테 딱이야!
클릭 이벤트가 드래그 가능하거나 정렬 가능한 이벤트 후에 정의 된 경우에만 클릭 이벤트가 작동하지 않는 것 같다고 여기에 추가하고 싶습니다. 클릭이 먼저 추가되면 드래그시 활성화됩니다.
나는 타이머를 사용하거나 방지하는 것을 정말로 좋아하지 않으므로 내가 한 일은 다음과 같습니다.
var el, dragged
el = $( '#some_element' );
el.on( 'mousedown', onMouseDown );
el.on( 'mouseup', onMouseUp );
el.draggable( { start: onStartDrag } );
onMouseDown = function( ) {
dragged = false;
}
onMouseUp = function( ) {
if( !dragged ) {
console.log('no drag, normal click')
}
}
onStartDrag = function( ) {
dragged = true;
}
바위처럼 단단한..
표준 jQuery 클릭 기능을 사용하는 것을 발견했습니다.
$("#element").click(function(mouseEvent){ // click event });
works just fine in jQuery UI. The click event will not be executed when dragging and dropping. :)
lex82's version but for .sortable()
start: function(event, ui){
ui.item.find('.ui-widget-header').addClass('noclick');
},
and you may only need:
start: function(event, ui){
ui.item.addClass('noclick');
},
and here's what I'm using for the toggle:
$("#datasign-widgets .ui-widget-header").click(function(){
if ($(this).hasClass('noclick')) {
$(this).removeClass('noclick');
}
else {
$(this).next().slideToggle();
$(this).find('.ui-icon').toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
}
});
A possible alternative for Sasha's answer without preventing default:
var tmp_handler;
.sortable({
start : function(event,ui){
tmp_handler = ui.item.data("events").click[0].handler;
ui.item.off();
},
stop : function(event,ui){
setTimeout(function(){ui.item.on("click", tmp_handler)}, 300);
},
In jQuery UI, elements being dragged are given the class "ui-draggable-dragging".
We can therefore use this class to determine whether to click or not, just delay the event.
You don't need to use the "start" or "stop" callback functions, simply do:
$('#foo').on('mouseup', function () {
if (! $(this).hasClass('ui-draggable-dragging')) {
// your click function
}
});
This is triggered from "mouseup", rather than "mousedown" or "click" - so there's a slight delay, might not be perfect - but it's easier than other solutions suggested here.
After reading through this and a few threads this was the solution I went with.
var dragging = false;
$("#sortable").mouseover(function() {
$(this).parent().sortable({
start: function(event, ui) {
dragging = true;
},
stop: function(event, ui) {
// Update Code here
}
})
});
$("#sortable").click(function(mouseEvent){
if (!dragging) {
alert($(this).attr("id"));
} else {
dragging = false;
}
});
Have you tried disabling the link using event.preventDefault(); in the start event and re-enabling it in the drag stopped event or drop event using unbind?
Just a little wrinkle to add to the answers given above. I had to make a div that contains a SalesForce element draggable, but the SalesForce element has an onclick action defined in the html through some VisualForce gobbledigook.
Obviously this violates the "define click action after the drag action" rule, so as a workaround I redefined the SalesForce element's action to be triggered "onDblClick", and used this code for the container div:
$(this).draggable({
zIndex: 999,
revert: true,
revertDuration: 0,
start: function(event, ui) {
$(this).addClass('noclick');
}
});
$(this).click(function(){
if( $(this).hasClass('noclick'))
{
$(this).removeClass('noclick');
}
else
{
$(this).children(":first").trigger('dblclick');
}
});
The parent's click event essentially hides the need to double-click the child element, leaving the user experience intact.
I tried like this:
var dragging = true;
$(this).click(function(){
if(!dragging){
do str...
}
});
$(this).draggable({
start: function(event, ui) {
dragging = true;
},
stop: function(event, ui) {
setTimeout(function(){dragging = false;}, 300);
}
});
In my case it worked like this:
$('#draggable').draggable({
start: function(event, ui) {
$(event.toElement).one('click', function(e) { e.stopPropagation(); });
}
});
참고URL : https://stackoverflow.com/questions/1771627/preventing-click-event-with-jquery-drag-and-drop
'program story' 카테고리의 다른 글
이 IP, 사이트 또는 모바일 애플리케이션은이 API 키를 사용할 권한이 없습니다. (0) | 2020.09.21 |
---|---|
moment.js에서 날짜 만 비교하는 방법 (0) | 2020.09.21 |
CSS를 사용하여 셀 사이에 공백 추가 (td) (0) | 2020.09.21 |
jQuery 플러그인 : 콜백 기능 추가 (0) | 2020.09.21 |
타임 스탬프 형식으로 현재 NSDate 가져 오기 (0) | 2020.09.20 |