gpt4 book ai didi

jquery - 防止父级触发子事件时 jquery 可拖动

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

我将 jquery Draggable 附加到 DIV 容器,它的每个子元素都有一个单击事件,如何防止在拖动主父容器时触发子事件。

我只想在单击子事件时触发子事件,而不是在拖动整个事件时触发。

我做了一个演示:http://jsfiddle.net/sygad/RgdPq/1/

感谢任何帮助。

最佳答案

您可以使用临时变量来跟踪拖动状态,然后从单击事件更改为 mouseup 事件,如下所示 jsFiddle example

jQuery

var bodyWidth = $(window).width();
var bodyHeight = $(window).height();
var dragging = false;
$("#container").draggable({
containment: "window",
start: function() {
dragging = true;
$(this).addClass('dragged')
},
stop: function() {
dragging = false;
$(this).removeClass('dragged')
}
});

$('.box').mouseup(function() {
if (!dragging) {
//If there is already a new box present, remove it
if ($('.newBox').length) {
$('.newBox').remove();
}

//Get the offset of THIS box we just clicked
var thisOffset = getOffset(this)

//Get its left & top value
var newBoxLeft = thisOffset.left;
var newBoxTop = thisOffset.top;

//Full size box will be 75% width & height of viewport
var newBoxFinalWidth = bodyWidth * 0.75;
var newBoxFinalHeight = bodyHeight * 0.75;

//Full size box will be positioned center/center on the screen
var newBoxDestLeft = (bodyWidth - newBoxFinalWidth) / 2;
var newBoxDestTop = (bodyHeight - newBoxFinalHeight) / 2;

//Create our new box
var newBox = '<div class="newBox clickOut"></div>'

//Add it to the DOM
$('body').append(newBox);

//Position it to overlay the box we just clicked
$('.newBox').css({
'left': newBoxLeft,
'top': newBoxTop
})

//Animate it from the orig box position to its final width/height & left/top
$('.newBox').delay(100).animate({
'width': newBoxFinalWidth,
'height': newBoxFinalHeight,
'left': newBoxDestLeft,
'top': newBoxDestTop
}, 2000, 'easeOutExpo')
}
})

//Clickout function
$(document).click(function(e) { /*if parent of this click is NOT clickout AND this click is NOT clickout then hide stuff*/
if ($(e.target).parents().is('.clickOut') == false && $(e.target).is('.clickOut') == false) {
clickOut();
}
});

function clickOut() {
$('.newBox').remove()
}

function getOffset(item) {
var cssOffset = $(item).offset();
var cssLeft = parseInt(cssOffset.left);
var cssTop = parseInt(cssOffset.top);

return {
'left': cssLeft,
'top': cssTop
};
}​

关于jquery - 防止父级触发子事件时 jquery 可拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11801767/

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