jQuery에서 "드래깅"을 감지할 수 있습니까?
사용자가 링크를 클릭하면 나타나는 욱신거림이 있습니다.
문제는 같은 링크를 클릭하고 드래그해서 재배치할 수 있다는 것입니다.이런 경우라면, 저는 등장하는 데 고동을 부릴 필요가 없을 것입니다.실제로 어디론가 가기를 기다리는 경우에만 표시하면 됩니다.
jQuery를 사용하여 클릭 및 드래그가 아닌 링크에 대한 클릭일 경우에만 트렁커가 나타날 수 있는 이벤트 수신기를 만들 수 있는 방법은 무엇입니까?
마우스 아래에서 상태 설정을 시작하고, 마우스 이동 이벤트가 발생하면 기록하고, 마지막으로 마우스 위에서 마우스가 이동했는지 확인합니다.움직였다면 계속 끌고 있는 겁니다우리가 움직이지 않았다면 클릭입니다.
var isDragging = false;
$("a")
.mousedown(function() {
isDragging = false;
})
.mousemove(function() {
isDragging = true;
})
.mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
if (!wasDragging) {
$("#throbble").toggle();
}
});
데모: http://jsfiddle.net/W7tvD/1399/
어떤 이유에서인지 위의 해결책들은 저에게 효과가 없었습니다.저는 다음과 같이 했습니다.
$('#container').on('mousedown', function(e) {
$(this).data('p0', { x: e.pageX, y: e.pageY });
}).on('mouseup', function(e) {
var p0 = $(this).data('p0'),
p1 = { x: e.pageX, y: e.pageY },
d = Math.sqrt(Math.pow(p1.x - p0.x, 2) + Math.pow(p1.y - p0.y, 2));
if (d < 4) {
alert('clicked');
}
})
거리 제한을 원하는 대로 조정할 수도 있고, 심지어 0까지 취할 수도 있습니다.
jQuery UI로 이렇게 하면 됩니다.
$( "#draggable" ).draggable({
start: function() {
},
drag: function() {
},
stop: function() {
}
});
$(".draggable")
.mousedown(function(e){
$(this).on("mousemove",function(e){
var p1 = { x: e.pageX, y: e.pageY };
var p0 = $(this).data("p0") || p1;
console.log("dragging from x:" + p0.x + " y:" + p0.y + "to x:" + p1.x + " y:" + p1.y);
$(this).data("p0", p1);
});
})
.mouseup(function(){
$(this).off("mousemove");
});
이 솔루션은 "on" 및 "off" 기능을 사용하여 마우스 이동 이벤트를 바인딩 해제합니다(bind 및 unbind는 더 이상 사용되지 않음).또한 두 개의 마우스 이동 이벤트 사이에서 마우스 x 및 y 위치의 변화를 감지할 수 있습니다.
시도해 보십시오. 언제 '드래그' 상태인지 표시됩니다.;) 피들 링크
$(function() {
var isDragging = false;
$("#status").html("status:");
$("a")
.mousedown(function() {
$("#status").html("status: DRAGGED");
})
.mouseup(function() {
$("#status").html("status: dropped");
});
$("ul").sortable();
});
// here is how you can detect dragging in all four directions
var isDragging = false;
$("some DOM element").mousedown(function(e) {
var previous_x_position = e.pageX;
var previous_y_position = e.pageY;
$(window).mousemove(function(event) {
isDragging = true;
var x_position = event.pageX;
var y_position = event.pageY;
if (previous_x_position < x_position) {
alert('moving right');
} else {
alert('moving left');
}
if (previous_y_position < y_position) {
alert('moving down');
} else {
alert('moving up');
}
$(window).unbind("mousemove");
});
}).mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
$(window).unbind("mousemove");
});
마우스 업 이벤트를 들을 때 부작용이 발생하지 않도록 요소의 드래그 가능 속성을 false로 설정해야 합니다.
<div class="thing" draggable="false">text</div>
그런 다음 jQuery를 사용할 수 있습니다.
$(function() {
var pressed, pressX, pressY,
dragged,
offset = 3; // helps detect when the user really meant to drag
$(document)
.on('mousedown', '.thing', function(e) {
pressX = e.pageX;
pressY = e.pageY;
pressed = true;
})
.on('mousemove', '.thing', function(e) {
if (!pressed) return;
dragged = Math.abs(e.pageX - pressX) > offset ||
Math.abs(e.pageY - pressY) > offset;
})
.on('mouseup', function() {
dragged && console.log('Thing dragged');
pressed = dragged = false;
});
});
클릭을 누르고 끌 때만 실행하도록 허용된 답변에서 분기했습니다.
마우스를 누르고 있지 않을 때는 기능이 실행되고 있었습니다.이 기능을 원하는 경우 업데이트된 코드는 다음과 같습니다.
var isDragging = false;
var mouseDown = false;
$('.test_area')
.mousedown(function() {
isDragging = false;
mouseDown = true;
})
.mousemove(function(e) {
isDragging = true;
if (isDragging === true && mouseDown === true) {
my_special_function(e);
}
})
.mouseup(function(e) {
var wasDragging = isDragging;
isDragging = false;
mouseDown = false;
if ( ! wasDragging ) {
my_special_function(e);
}
}
);
이렇게 간단한 방법은 터치 시작, 터치 이동 및 터치 끝입니다.PC와 터치기기 모두 가능합니다. jquery documentation에서 확인하고 이것이 당신에게 가장 좋은 해결책이기를 바랍니다. 행운을 빌어요.
시멘 에흐홀트의 답변을 기반으로 한 jQuery 플러그인.클릭 한 번으로 불렀어요.
/**
* jQuery plugin: Configure mouse click that is triggered only when no mouse move was detected in the action.
*
* @param callback
*/
jQuery.fn.singleclick = function(callback) {
return $(this).each(function() {
var singleClickIsDragging = false;
var element = $(this);
// Configure mouse down listener.
element.mousedown(function() {
$(window).mousemove(function() {
singleClickIsDragging = true;
$(window).unbind('mousemove');
});
});
// Configure mouse up listener.
element.mouseup(function(event) {
var wasDragging = singleClickIsDragging;
singleClickIsDragging = false;
$(window).unbind('mousemove');
if(wasDragging) {
return;
}
// Since no mouse move was detected then call callback function.
callback.call(element, event);
});
});
};
사용 중:
element.singleclick(function(event) {
alert('Single/simple click!');
});
^^
파티에 늦었지만, 이 코드는 터치 이벤트(모바일, 태블릿)도 감지합니다.
$(".draggable").on('touchstart mousedown', function(ev) {
ev.preventDefault();
$(this).on("touchmove mousemove",function(e){
var x = e.pageX || e.changedTouches[0].pageX;
var y = e.pageY || e.changedTouches[0].pageY;
var p1 = { x: x, y: y };
var p0 = $(this).data("p0") || p1;
console.log("dragging from x:" + p0.x + " y:" + p0.y + "to x:" + p1.x + " y:" + p1.y);
$(this).data("p0", p0);
});
}).on('touchend mouseup', function(ev) {
ev.preventDefault();
$(this).off("touchmove mousemove");
});
타이머를 설정하셔야 합니다.타이머가 시간을 초과하면 욱신거림을 시작하고 클릭을 등록합니다.드래그가 발생하면 타이머가 완료되지 않도록 타이머를 지웁니다.
jQueryUI를 사용하는 경우 - onDrag 이벤트가 있습니다.그렇지 않은 경우 청취자를 클릭()이 아닌 마우스업()에 연결합니다.
변수를 설정할 필요 없이 데이터 속성에서 이동하는지 설정할 수 있습니다.
$youtubeSlider.find('a')
.on('mousedown', function (e) {
$(this).data('moving', false);
})
.on('mousemove', function (e) {
$(this).data('moving', true);
})
.on('mouseup', function (e) {
if (!$(this).data('moving')) {
// Open link
}
});
항상 마우스 위치를 추적하고 왼쪽, 오른쪽, 위쪽, 아래쪽 드래그를 감지하는 기능이 필요했습니다.클릭 시 트리거되지 않지만 최소 15px 이동이 필요합니다.
/**
* Check for drag when moved minimum 15px
* Same time keep track of mouse position while dragging
*/
// Variables to be accessed outside in other functions
var dragMouseX;
var dragMouseY;
var myDragging = false; // true or false
var dragDirectionX = false; // left or right
var dragDirectionY = false; // top or bottom
$(document).on("mousedown", function(e) {
// Reset some variables on mousedown
var lastDirectionCheck = e.timeStamp;
var dragStartX = e.pageX;
var dragStartY = e.pageY;
dragMouseX = e.pageX;
dragMouseY = e.pageY;
myDragging = false;
dragDirectionX = false;
dragDirectionY = false;
// On the move
$(document).on("mousemove", function(e) {
dragMouseX = e.pageX;
dragMouseY = e.pageY;
// Recalculate drag direction every 200ms in case user changes his mind
if (e.timeStamp > (lastDirectionCheck + 200)) {
dragStartX = dragMouseX;
dragStartY = dragMouseY;
lastDirectionCheck = e.timeStamp;
}
// Check for drag when moved minimum 15px in any direction
if (!myDragging && Math.abs(dragStartX - dragMouseX) > 15 || Math.abs(dragStartY - dragMouseY) > 15) {
myDragging = true;
}
if (myDragging) {
// Check drag direction X
if (dragStartX > dragMouseX) dragDirectionX = 'left';
if (dragStartX < dragMouseX) dragDirectionX = 'right';
// Check drag direction Y
if (dragStartY > dragMouseY) dragDirectionY = 'top';
if (dragStartY < dragMouseY) dragDirectionY = 'bottom';
// console.log(dragDirectionX + ' ' + dragDirectionY);
}
});
});
// Reset some variables again on mouseup
$(document).on("mouseup", function() {
$(document).off("mousemove");
myDragging = false;
dragDirectionX = false;
dragDirectionY = false;
});
언급URL : https://stackoverflow.com/questions/4127118/can-you-detect-dragging-in-jquery
'sourcecode' 카테고리의 다른 글
오라클 10g small Blob 또는 Clob이 인라인으로 저장되지 않습니까? (0) | 2023.09.10 |
---|---|
jquery 중첩 ajax 호출 서식 지정 (0) | 2023.09.10 |
알 수 없는 콜백 매개 변수 수가 있는 Axios spread() (0) | 2023.09.10 |
정렬 목적으로 두 문자열을 알파벳 순으로 비교 (0) | 2023.09.10 |
도커가 Windows에서 실행 중인지 확인하는 방법은 무엇입니까? (0) | 2023.09.10 |