2011-05-03 30 views
5

是否可以從中心向外而不是從左向右(以及從上到下)生成一張圖片?我試圖實現的效果類似於燈箱,當您單擊圖像並向外擴展時。使用Jquery Animate調整圖像的尺寸

謝謝!

+0

我沒有測試過這一點,所以這仍將是一個評論,但你能不能改變動畫的寬度/高度,然後頂部/左側,頂部/左側是寬度/高度變化的一半。 – Robert 2011-05-03 14:09:27

回答

2

@Aron的解決方案是可以的,但它具有一定的侷限性:文檔流程中不能有圖像。

我的解決方案實際上創建了一個絕對定位的圖像克隆,並將其顯示在原始圖像的頂部。它使用.offset()來計算原始圖像的絕對位置。

這種方法的缺點是,如果文檔流量的變化(如調整大小客戶端窗口時),絕對定位元件保持在舊的位置這一點。這取決於你的頁面佈局,如果你可以使用這種方法或不。

單擊我的演示中的圖像切換效果。 http://jsfiddle.net/Xhchp/3/

HTML:

<p>Some random text.</p> 
<p>More blah. <img id="someImage" src="http://upload.wikimedia.org/wikipedia/commons/thumb/1/16/Deletion_icon.svg/600px-Deletion_icon.svg.png"/> More blah.</p> 
<p>Some random text.</p> 

CSS:

#someImage { width:32px; height:32px; } 

的javascript:

function ZoomIn(){ 
    var p = $(this).offset(); 
    var w = $(this).width(); 
    var h = $(this).height(); 
    var $clone = $(this).clone(); 
    $clone.css({ 
     position: "absolute", 
     left: p.left + "px", 
     top: p.top + "px", 
     "z-index": 2 
    }).appendTo('body'); 
    $clone.data("origWidth",w); 
    $clone.data("origHeight",h); 
    $clone.data("origTop",p.top); 
    $clone.data("origLeft",p.left); 
    $clone.animate({ 
     top: "-=" + Math.floor(h * 0.5), 
     left: "-=" + Math.floor(w * 0.5), 
     width: Math.floor(w * 2), 
     height: Math.floor(h * 2) 
    },function(){ 
    }); 
    $clone.click(ZoomOut); 
} 

function ZoomOut(){ 
    var w = $(this).data("origWidth"); 
    var h = $(this).data("origHeight"); 
    var t = $(this).data("origTop"); 
    var l = $(this).data("origLeft"); 
    $(this).animate({ 
     top: t, 
     left: l, 
     width: w, 
     height: h 
    },function(){ 
     $(this).remove(); 
    }); 
} 

$(function(){ 
    $('img').click(ZoomIn); 
}); 
10

這應該不是太難:

// increase factor 
var factor = 2; 

$('#foo').click(function() { 
    $(this).animate({ 
     top: '-=' + $(this).height()/factor, 
     left: '-=' + $(this).width()/factor, 
     width: $(this).width() * factor 
    }); 
}); 

這是如何實現的:

  • 圖像的尺寸以一定的比例增加。在這種情況下,這是* 2,但我可以想象你想做一些聰明的事情,並且有一個上限左右。
  • 隨着當前尺寸除以增加因子,圖像頂部和左側偏移量減小。

Quick demo here.

2

如果我的理解沒錯,here is what you want

我用position: absolute顯示大圖像,那麼您的佈局不會受到被調整大小的圖像的影響。如果您對此解決方案有疑問,請在這裏發表評論。

+0

你怎麼會去toggeling這個功能呢? – Studiostefan 2012-07-08 18:29:13