使用css3里面的transform属性可以达到这个效果
参考:http://blog.sina.com.cn/s/blog_abba9c1d0101e0sx.html
下面是我写的和jquery结合使用的一个例子:
//width、height为div的宽和高
//imageWidth、imageHeight为图片的实际宽和高
vardiv =$('<div></div>');//image放在div里
var img =$('<img src="' + 'images/' + data.imageName +'"></img>');
div.css({ //这个div的样式随便定义
'position':'absolute',
'top':0,
'left':0,
'width':width,
'height':height,
'background-color': 'rgb(0, 0,0)'
});
varimageScale,
imageTop = (height - imageHeight) *0.5,
imageLeft = (width - imageWidth) *0.5;
if (imageWidth / imageHeight< width / height) { //判断哪个边长
imageScale = height / imageHeight; //等比例缩放的比例
}else {
imageScale = width /imageWidth;
}
img.css({
'position':'absolute',
'top':imageTop,//使图片在div里垂直居中
'left':imageLeft, //使图片在div里左右居中
'width':imageWidth,
'height':imageHeight,
'-webkit-transform':'scale(' + imageScale +')',//等比例缩放
'-moz-transform':'scale(' + imageScale +')',
'-ms-transform':'scale(' + imageScale +')'
});
img.appendTo(div);
div.appendTo(element);
下面的内容转自:http://blog.sina.com.cn/s/blog_62ebc63a0100l9y9.html
图片撑破页面,相信大家会有被困扰的时候,或许是以前,或许是现在,但不要紧了,jquery帮你两行代码就解决问题,让图片被受控制。
代码如下:
$(document).ready(function(){
var ywidth = 500;//初始最大宽度
$(”img”).each(function(){
if($(this).width()> ywidth) {
$(this).width(ywidth);
}
});
});
把它加到网页上立杆见影,让图片不在头痛。有的朋友可能会想查看大图,那没问题,再加几行代码,加个点击查看大图的效果。
代码如下:
$(document).ready(function(){
var ywidth = 450;//初始最大宽度
$(”img”).each(function(){
if($(this).width()> ywidth) {
$(this).width(ywidth);
$(this).mouseover(function(){
$(this).css(”cursor”,”hand”);
});
$(this).click(function(){
window.location.href= $(this).attr(”src”);
});
}
});
});
图片撑破容器是很煞风景的事情,不牵扯到后台生成缩略图的解决方法是在前端对于撑破容器的图片,指定width="100%",则图片会自动适应父容器的宽度。虽然难看了一点,但不失为一个经济且花费小的方法。
用JS简单的实现思路就是遍历所有页面图片,对于宽度大于父元素的,添加width属性,当然根据需要还可以加上Lightbox之类的特效。