最近一個項目要作一個圖片縮放特效,以下:css
原始是小圖片html
點擊右下角的加號後變成大圖片jquery
再點擊大圖片右下角的縮小標記,又回到初始狀態。css3
由於這個特效用到的圖片大部分不是很大,因而準備利用jquery來改變圖片邊框的寬高,再用css3的transform屬性來改變圖片的大小。web
html代碼以下:chrome
<div class="click_to_zoom"><img src="http://imgstatic.baidu.com/img/image/sheying320s.jpg" alt="" /><a href="#">點擊</a></div>
下面的代碼即頁面加載時獲取圖片的寬高,除以2.5倍之後再賦給圖片的父級,這樣父級就變小了。瀏覽器
$(document).ready(function() { //dom加載完成時,變大變小功能 $('.click_to_zoom a').toggle( function(e) { e = e || event; e.preventDefault(); $(this).siblings('img').addClass('zoom_big'); $(this).addClass('tosmall'); var img = $(this).siblings('img'); var theImage = new Image(); theImage.src = img.attr("src"); img.parent('.click_to_zoom').animate({ 'width': theImage.width, 'height': theImage.height }); }, function(e) { e = e || event; e.preventDefault(); $(this).siblings('img').removeClass('zoom_big'); $(this).removeClass('tosmall'); var img = $(this).siblings('img'); var theImage = new Image(); theImage.src = img.attr("src"); img.parent('.click_to_zoom').animate({ 'width': theImage.width / 2.5, 'height': theImage.height / 2.5 }); } ); $('.click_to_zoom').fadeIn(500); }); $(window).load( function() { // 圖片加載完成後獲取圖片的寬高 var img = $('.click_to_zoom img'); var theImage = new Image(); for (var i = img.length - 1; i >= 0; i--) { theImage.src = img.eq(i).attr("src"); img.eq(i).parent('.click_to_zoom').animate({ 'width': theImage.width / 2.5, 'height': theImage.height / 2.5 }); }; } )
css以下:dom
.click_to_zoom{ position: relative; border: 3px double #dcdcdc; margin: 20px auto; clear: both; display: none; width: 0px; overflow: hidden; padding: 5px; -moz-box-shadow: inset 0px 0px 10px #d5d5d5; -webkit-box-shadow: inset 0px 0px 10px #d5d5d5; box-shadow: inset 0px 0px 10px #d5d5d5; } .click_to_zoom a{ text-indent: -100px; overflow: hidden; display: block; width: 24px; height: 24px; position: absolute; bottom: 0; right: 0; background: url(tobig.png) 0 0 no-repeat; } .click_to_zoom img{ zoom:0.4; -moz-transform:scale(0.4); margin: 0 auto; } .click_to_zoom img.zoom_big{ zoom:1; -moz-transform:scale(1); } .click_to_zoom a.tosmall{ background: url(tosmall.png) 0 0 no-repeat; }
用ie,chrome測試都沒有問題,但在火狐裏測試時,發現小圖片的位置老是不對,以下:測試
後來,google了一下,從stackoverflow裏找到了答案,原來還得在css裏針對火狐加一句this
-moz-transform-origin:0 0;
這句就是對圖片位置的修正,加入後,各大大瀏覽器就兼容了。