js控制图片高度、宽度

JavaScript028

js控制图片高度、宽度,第1张

//给你一个比较灵活的,可自由控制

jQuery(window).load(function () {

jQuery(".div1 img").each(function () {//div1下的img宽度、高度设置

DrawImage(this, 700, 470)//宽700,高470,自己改为相同即可。

})

})

function DrawImage(ImgD, FitWidth, FitHeight) {//下面是判断,可自己修改条件

var image = new Image()

image.src = ImgD.src

if (image.width > 0 && image.height > 0) {

if (image.width / image.height >= FitWidth / FitHeight) {

if (image.width > FitWidth) {

ImgD.width = FitWidth

ImgD.height = (image.height * FitWidth) / image.width

}else {

ImgD.width = image.width

ImgD.height = image.height

}

} else {

if (image.height > FitHeight) {

ImgD.height = FitHeight

ImgD.width = (image.width * FitHeight) / image.height

} else {

ImgD.width = image.width

ImgD.height = image.height

}

}

}

}

这种情况用CSS来控制最合适。例如你想让初始图片显示为100px*100px,则:

<img src="images/pic.png" width="100" height="100" />

或者:

<img src="images/pic.png" style="width:100pxheight:100px" />

当页面中图片非常多,且要求每张图片的大小依据其父容器来固定怎么办?可以使用max-weight:

img {max-weight:100%}

这样图片会自动缩放到和其父容器等宽。