2010-09-02 70 views
4

晚上全部 - 什麼是動態訪問圖像高度和寬度的最佳方式。
我想添加20%的圖像的寬度和高度,並當周圍的div被徘徊時動畫,我想我需要使用'this',但不知道如何訪問圖像。Jquery - 在懸停時擴大圖像高度和寬度20%

任何幫助很好地收到。

乾杯保羅

回答

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(),由於尺寸可能尚未裝載。

7

使用widthheight的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); 
}); 
+0

酷,歡呼隊友 – Dancer 2010-09-02 21:06:17

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

這裏是一種用動畫做,它應該提供一個平滑的過渡:

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

這將無法正常工作相當預期,因爲如果你在懸停輸入/輸出在動畫結束之前,新的'.height()'和'.width()'值將不會是它們的目標值,這意味着它會回到其他大小:)嘗試在這裏:http:// jsfiddle .net/nick_craver/JqDMR /我做的唯一更改是'$ this'沒有在您的代碼中定義:) – 2010-09-02 20:11:27