jQuery create div on mouseclick

2019-09-05 17:05发布

问题:

On my site I want to be able to create a div when I click my mouse, the div should be created next to where the mouse clicked. I then want to be able to animate this div to fly off the bottom of the screen.

So far I have this jQuery code that simply shows a div on click, however I want it to animate down and off screen each time it is displayed. Can anybody help me out here.

$("#divId").hide();
$(".holder").click( function(event) {
    $("#divId").show().css( {position:"absolute", top:event.pageY, left: event.pageX})
});

and a JSfiddle: http://jsfiddle.net/VZY6C/

回答1:

You can easily make use of jquerys animate function.

$(".holder").click( function(event) {
    $("#divId").show().css( {position:"absolute", top:event.pageY, left: event.pageX}).stop().animate({
        top: 800
    }, 1000);
});

In this example you animate the top property from what it is, to 800, within 1 second.

And then if you want it to dissapear hwen it leaves the box you just put position: relative; and overflow: hidden;

fiddle: http://jsfiddle.net/CL3Lu/

Edit: Just added the stop() function to the chain. This stops the currently running animation.

New fiddle: http://jsfiddle.net/Bq3Dc/

You can see the difference if you make multiple clicks fast.