Without using 开发者_如何学Goplug-ins, how would I check if an element is inside another? I tried using
element.hover();
but to no avail. Is this possible with pure JQuery, or should I look for a workaround?
The code currently looks like
$(document).ready(function(){
$(".element_to_drag").mousedown(function(){
$(this).addClass("dragging");
$(".dragging").live("mousemove", function(e) {
var offset = $("#container").offset();
var x = offset.left;
var y = offset.top;
$(this).css("position", "absolute");
$(this).css("left", e.pageX - x);
$(this).css("top", e.pageY - y);
})
$(".dragging").live("mouseup", function(e)
{
$(this).removeClass("dragging");
})
$("#elementContainer").hover(function()
{
$(".dragging").css("background-color", "red");
});
});
});
I'm very much still learning, feel free to critique anything.
Update your mousemove function to contain this instead:
$(this).css("position", "absolute");
$(this).css("left", e.pageX - $(this).width()/2);
$(this).css("top", e.pageY - $(this).height()/2);
$(this)
refers to your draggable object. Then all you need to do to see if the draggable object is contained inside the #container
is if an if statement that checks if $(this).css("left") is greater than the X position (not offset: see http://api.jquery.com/position/) of the container.
Of course you might want to do some checks as well to look at the width of the draggable item and ensure that it sits entirely inside the container.
精彩评论