做圖片放大效果時,若只改變 width 和 height 而不調整 left 與 top,圖片看起來並非從中心放大,而是偏向一側。本文示範如何讓圖片以中心為原點平滑放大。
普通放大的效果:

從中心點進行縮放的效果:

<meta charset="utf-8">
<style type="text/css">
#div1{
width:600px;
height:400px;
margin:50px auto;
position:relative;
text-align: center;
padding-left:50px;
}
#div1 img{
position:absolute;
left:0;
top:0;
margin: 0 auto;
}
</style>
<div id="div1">
<img src="images/1.jpg" width="100px" height="80px">
</div>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function(){
$('#div1 img').mouseenter(function(){
var wValue=1.5 * $(this).width();
var hValue=1.5 * $(this).height();
$(this).animate({width: wValue, height: hValue, left:("-"+(0.5 * $(this).width())/2), top:("-"+(0.5 * $(this).height())/2)}, 1000);
}).mouseleave(function(){
$(this).animate({width: "100", height: "80", left:"0px", top:"0px"}, 1000 );
});
});
</script>
關鍵在於放大時同步把 left 與 top 向負方向平移,抵消尺寸變化帶來的偏移,从而让图片以自身中心为基准平滑放大,移出后再恢复原位。
希望這段 JQuery 控制圖片中心放大的代碼對大家有所幫助。