2012-04-30 47 views
3

我希望能够增加(放大)和减小(缩小)图像并保持宽高比。在点击时增加/减少图像大小以保持宽高比

我已经创建了一个简单的例子,但不知道如何保持宽高比。

减少时是否可以设置最小尺寸?

感谢

HTML

<div id="image-container"> 
    <img src="Image.jpg" alt=""/> 
</div> 
<div id="image-controls"> 
    <input id="zoom-in" value="+" type="submit" /> 
    <input id="zoom-out" value="-" type="submit" /> 
</div> 

JQuery的

$(document).ready(function() { 

var img = $('#image-container img'); 
var zoomWidthIncrement = img.width() * 1/3; 
var zoomHeightIncrement = img.height() * 1/3; 

$("#zoom-in").click(function (e){ 
    img.css({width: img.width() + zoomWidthIncrement, height: img.height() + zoomHeightIncrement}); 
e.preventDefault(); 
}); 

$("#zoom-out").click(function (e){ 
    img.css({width: img.width(function(i, w) { return w - zoomWidthIncrement; }), height: img.height(function(i, w) { return w - zoomWidthIncrement; }) 
}); 
e.preventDefault(); 
}); 
}); 

回答

1

只要改变宽度或高度,而不是两个。浏览器将按比例自动缩放图像。

jsFiddle example

+0

谢谢,这是诀窍!此外,为了避免图像在减少时消失,我只在CSS中为图像添加了最小宽度。 – luke2012

相关问题