最近一个项目要做一个图片缩放特效,如下:
原始是小图片
点击右下角的加号后变成大图片
再点击大图片右下角的缩小标记,又回到初始状态。
因为这个特效用到的图片大部分不是很大,于是准备利用jquery来改变图片边框的宽高,再用css3的transform属性来改变图片的大小。
html代码如下:
<div class="click_to_zoom"><img src="/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如下:
.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里针对火狐加一句
-moz-transform-origin:0 0;
这句就是对图片位置的修正,加入后,各大大浏览器就兼容了。