我在带有类的 div
上使用拖动功能(不是 jquery UI,我不想要 Jquery UI),但我有更多的 div
同一个类,如何拦截点击this div
这是我的代码:
$(function(){
var dragging = false;
var iX, iY;
// how can I intercept $(this, ".marker") ??
$(".marker").mousedown(function(e) {
dragging = true;
iX = e.clientX - this.offsetLeft;
iY = e.clientY - this.offsetTop;
this.setCapture && this.setCapture();
return false;
});
document.onmousemove = function(e) {
if (dragging) {
var e = e || window.event;
var oX = e.clientX - iX;
var oY = e.clientY - iY;
// how can I find the ID related to this div ?
$('.marker').css({"left":oX + "px", "top":oY + "px"});
return false;
}
};
$(document).mouseup(function(e) {
dragging = false;
// $(".marker")[0].releaseCapture();
e.cancelBubble = true;
})
})
这里是原始codePen https://codepen.io/Jonh/pen/jgyLB
这里是创建div的JS,是JS动态创建的
for (i = 0; i < theFeat.length; i++) {
markerText = theFeat[i].value;
mk_totalHeight += 50;
$('<div>', { id: 'd' + i, style:"top:" + mk_totalHeight + "px;"}).addClass('marker').appendTo('#map');
$('<div>', { id: i, style:"background-image:url('../../../symbols/marker" + (i + 1) + ".png');" }).addClass('markerIcon').appendTo('#d'+ i);
$('<span>', { id: 's' + i, text: markerText}).appendTo('#d' + i);
} // end for loop
如果你只有一个 div
这很有用,但我如何在一个位于不同 div
上的类上实现它,我必须复制该函数并添加为选择ID? (允许的最大 div
为 4,因此它将是 #d0
、#d1
、#d2
、#d3
)
最佳答案
所以你的一位听众,
// how can I intercept $(this, ".marker") ??
$(".marker").mousedown(function(e) {
dragging = true;
iX = e.clientX - this.offsetLeft;
iY = e.clientY - this.offsetTop;
this.setCapture && this.setCapture();
return false;
});
...事实上,不会像您期望的那样工作。因为 .marker
元素是动态创建的,所以它们的事件监听器将失败。相反,监听最近的父节点:
// Try something like this:
$("#map").on("mousedown", ".marker", function(e){
// Either of the following should get to the element that
// triggered the mousedown
var target = $(this);
// OR YOU CAN USE
var target = $(e.currentTarget);
// ... whatever other processing you need...
});
关于javascript - Jquery多个div同一个类,只拖 "this"div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48285746/