我有两个 div:
<div class="main">
<div class="child" />
</div>
我为主元素创建了一个事件监听器,它使用户能够拖动子元素
map.bind('touchmove', function(f) {
if (map.pinch) {
return;
}
f.preventDefault();
f.originalEvent.preventDefault();
f = f.originalEvent.touches[0];
map.handleMoveEvent(f);
});
map.handleMoveEvent = function(f) {
mover.css('left', map.getX() + (f.clientX - map.lastmouse.clientX) / scaler.scale);
mover.css('top', map.getY() + (f.clientY - map.lastmouse.clientY) / scaler.scale);
map.lastmouse = f;
map.moverMoved();
}
map.moverMoved = function() {
if (map.getX() > 0) {
map.tileX--;
mover.moveX(-TILE_WIDTH);
map.find(".child").moveX(TILE_WIDTH);
map.updateVisibleTiles();
}
if (map.getX() < -TILE_WIDTH) {
map.tileX++;
mover.moveX(TILE_WIDTH);
map.find(".child").moveX(-TILE_WIDTH);
map.updateVisibleTiles();
}
if (map.getY() > 0) {
map.tileY--;
mover.moveY(-TILE_HEIGHT);
map.find(".child").moveY(TILE_HEIGHT);
map.updateVisibleTiles();
}
if (map.getY() < -TILE_HEIGHT) {
map.tileY++;
mover.moveY(TILE_HEIGHT);
map.find(".child").moveY(-TILE_HEIGHT);
map.updateVisibleTiles();
}
$('#console').html(map.tileX + " " + map.tileY);
//$('#console').html(map.getX() + " " + map.getY());
};
map.updateVisibleTiles = function() {
mover.find(".child").remove();
for (x = Math.max(map.tileX - tiledistance, 0); x <= Math.min(map.tileX + tiledistance, map.getTileCount() - 1); x++) {
for (y = Math.max(map.tileY - tiledistance, 0); y <= Math.min(map.tileY + tiledistance, map.getTileCount() - 1); y++) {
var child = $(document.createElement('div'));
child.width(TILE_WIDTH);
child.height(TILE_HEIGHT);
var farbe = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
child.css("background-color", farbe);
child.css('position', 'absolute');
child.addClass('child');
child.css('left', (x - map.tileX) * TILE_WIDTH);
child.css('top', (y - map.tileY) * TILE_HEIGHT);
mover.append(child);
}
}
}
在某些情况下,我必须在拖动时交换 child
$('.main').find(".child").remove();
但是移除后 touchmove 不再触发。仅当我通过点击子元素启动 touchmove 时才会发生这种情况...这个问题对我来说很明显,但是解决方案是什么?
最佳答案
$().remove()
删除 dom 元素及其事件监听器。使用 $().detach()
保留事件监听器。
The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.
关于javascript - 删除子项时 jQuery touchmove 停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24126738/