简体   繁体   中英

Shrinking an image to the coordinates of a mouse click position? (jQuery)

I'm pretty new to this, but I've been fiddling around trying to get an image to shrink to nothing on a central point, which works fairly well using a combination of the below code and relative positioning in the CSS.

 $(function() { $('#imageID').on('click', function() { $(this).animate({ width: 0, height: 0, top: '185px', left: '-2px' }, 200); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

What I'd like to be able to do, however, is to change this so that the image shrinks centred on the point where the click was made. I've had a go at trying out absolute positioning and trying to set the top / left to the values of pageX and pageY (and also with the extra step of assigning them to variables) but no dice.

Does anyone have any idea of how / if this can be done? Thanks.

First of all welcome to Stack Overflow!

How about using CSS animations for this?

Use transform instead of width and height in animations for a better performance.


CODE SNIPPET:

 $(function() { $('#imageID').on('click', function() { $(this).addClass("shrink"); }); }); 
 .shrink { animation: shrink 300ms linear forwards; } @keyframes shrink { to { transform: scale(0); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img id="imageID" src="http://fillmurray.com/300/300"> 


Here's more info on CSS transform and animation properties.

 $(function() { $('#imageID').on('click', function() { $(this).animate({ width: 0, height: 0, top: '185px', left: '-2px' }, 200); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM