Jquery - 悬停时将图像高度和宽度扩展20%

时间:2010-09-02 19:58:25

标签: jquery this jquery-animate

晚上所有 - 什么是动态访问图像高度和宽度的最佳方式 我希望在图像的宽度和高度上加20%,并在周围的div悬停时动画,我想我需要使用'this',但不知道如何访问图像。

任何得到很好的帮助。

干杯保罗

4 个答案:

答案 0 :(得分:8)

您可以使用.height().width()使用函数参数执行此类操作:

$("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,如果你想要一个平滑的动画,你可以存储初始高度/宽度和.animate(),如下所示:

$("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,请务必在$(window).load() $(document).ready()中运行其中任何一个选项,因为维度可能尚未加载。

答案 1 :(得分:7)

使用jQuery的widthheight方法:

$(".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);
});

答案 2 :(得分:1)

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

答案 3 :(得分:1)

这是一种使用animate的方法,它应该提供更平滑的过渡:

$("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
    });
});