简体   繁体   中英

How to change size of images?

I am trying to enlarge picture when user hovers to images and reduce the size of images after user mouseout the images.

I have the following codes

$('#image_layout').on('hover','img',function(){
    $(this).css('width','110%');
})

$('#image_layout').on('mouseout','img',function(){
    $(this).css('width','90%');
})

I want to enlarge the image from the center position of the image not from the top lefe position of the image.

The one I have:

 ----        ------
|    |  ->  |      |
 ----       |      |
             ------

The one I want: (enlarge the picture from center of the image)

               ------
   ----       |      | 
  |    |  --> |      |
   ----       |      |
               ------

I am not sure how to achieve this. Any tips? Thanks a lot!

Avoid using JavaScript for tasks that can be handled by simple CSS tweaks, don't make the weight of JavaScript on your page heavy.

#image_layout 
{
   width : /* initial width value */ 
   height: /* initial height value */
}


#image_layout : hover
{
   width : /* new width value */ 
   height: /* new height value */
   /* use of multiple tranistions */
   transition : all 0.2s ease-out 
}

Regarding the jQuery way,no need to apply .css() twice, just pass to it an object containing the properties with their values :

$('#image_layout').on('mouseout','img',function(){
    $(this).css({'width':'90%', 'height':'100%'});
});

When you change the width and you haven't defined the height yet, the browser automatically keeps the proportion between them, so the height will also be 110% and 90% .

Try this code:

$('#image_layout').on('hover','img',function(){
    $(this).css('width','110%')
        .css('height','100%')
});
$('#image_layout').on('mouseout','img',function(){
    $(this).css('width','90%')
        .css('height','100%');
});

What you want to achieve is not as easy as it seems. If you want to keep your origin in the center of the container you need to absolute position the image relative to the container. Try with this lil' plugin, it probably won't work for every case but it's worth a try.

$.fn.centerIt = function(){

    var height = this.outerHeight(),
        width = this.outerWidth();

    this.css({
        position: 'absolute',
        top: '50%',
        left: '50%',
        marginTop: -(height/2),
        marginLeft: -(width/2)
    })
    .parent()
    .css('position', 'relative');

    return this;    
};

$('img').css('width', '90%').centerIt();

Demo: http://jsfiddle.net/elclanrs/RMsSh/

Changing image size in JQuery is pretty easy. You can take this or the CSS approach with .CSS()

$('#imageId').width(150).height(100);

为了做到这一点,您需要将图像水平和垂直居中。

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