Jquery - Expand image height and width 20% on hover

僤鯓⒐⒋嵵緔 提交于 2019-12-21 02:45:09

问题


Evening all - Whats the best way to access an image's height and width dynamically .
I want to add 20% to an images width and height and animate when the surrounding div is hovered, I guess I need to use 'this', but not sure how to access the image.

Any help greatfully received.

Cheers Paul


回答1:


You could do something like this, using .height() and .width() with function arguments:

$("img").hover(function() {
    $(this).height(function(i, h) { return h * 1.2; })
           .width(function(i, w) { return w * 1.2; });
}, function() {
    $(this).height(function(i, h) { return h / 1.2; })
           .width(function(i, w) { return w / 1.2; });
});​

You can give it a try here, if you wanted a smooth animation you could store the initial height/width and .animate(), like this:

$("img").each(function() {
    $.data(this, 'size', { width: $(this).width(), height: $(this).height() });
}).hover(function() {
    $(this).stop().animate({ height: $.data(this,'size').height*1.2, 
                             width: $.data(this,'size').width*1.2 });
}, function() {
    $(this).stop().animate({ height: $.data(this,'size').height, 
                             width: $.data(this,'size').width });
});​

You can give it a try here, be sure to run either of these options in $(window).load(), and not $(document).ready(), since the dimensions may not be loaded yet.




回答2:


Use the width and height methods of jQuery:

$(".divs").mouseover(function() {

    var $div = $(this);
    var $item = $div.find("img");

    var width = $item.width();
    var height = $item.height();

    width = width * 1.2;
    height = height * 1.2;

    $item.width(width);
    $item.height(width);
});



回答3:


$("#divId").mouseover(function() {
    var o = $("#imgid");
    o.width(o.width()*1.2).height(o.height()*1.2);
});



回答4:


Here's a way to do it using animate, which should provide a smoother transition:

$("img").hover(function() {
    var $this = $(this);
    $this.animate({
        'height': $this.height() * 1.2,
        'width' : $this.width() * 1.2
    });
},function() {
       var $this = $(this);
       $this.animate({
        'height': $this.height() / 1.2,
        'width' : $this.width() / 1.2
    });
});


来源:https://stackoverflow.com/questions/3630734/jquery-expand-image-height-and-width-20-on-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!