想实现一个效果:假设有若干个高宽不同的图片,我想达到一个效果:1、比例不变。2、高宽不能超过某个值。3、尽量大。应该怎么实现?
本来想用css实现的,但发现css似乎实现不了第3点。只能用javascript了。
下面这个例子是使用了jquery的,仅为了看看效果,配图是随便找的:
![]() |
![]() |
![]() |
![]() |
因为想用源生js,所以很多东西懒得弄。直接把代码贴一下。
<html>
<head>
<style type="text/css">
td,input {width: 200px; height: 400px;}
</style>
</head>
<body>
<input type="text" />
<table>
<tbody>
<tr>
<td><img src="img/1.png" /></td>
<td><img src="img/2.png" /></td>
</tr>
<tr>
<td><img src="img/3.jpg" /></td>
<td><img src="img/4.jpg" /></td>
</tr>
</tbody>
</table>
</body>
<script type="text/javascript">
var input = document.getElementsByTagName("input")[0];
var toWidth = input.offsetWidth;
var toHeight = input.offsetHeight;
input.style.display = "none";//仅仅是想自动获取w,h。也可以在这写死。
var omw = function(e){
var kc;
if(navigator.userAgent.indexOf("Firefox")>0){kc = e;}
else {kc=event}
var img = kc.target;
var delta = kc.wheelDelta ? kc.wheelDelta : kc.detail*40;
var mul = (1+(delta/1200));
img.width = mul*img.width;
img.height = mul*img.height;
kc.preventDefault ? kc.preventDefault() : kc.returnValue= false;
return false;
};
var whp = toWidth/toHeight;
var imgs = document.getElementsByTagName("img");
for(var i=0;i<imgs.length;i++){
var _img = imgs[i];
if(document.addEventListener){
_img.addEventListener("DOMMouseScroll",function(e){
return omw(e);
}, false);
}
try{
_img.onmousewheel = function(e){return omw(e);};
}
catch (e){
//
}
var iWhp = _img.width/_img.height;
if(iWhp>whp){
_img.width = toWidth;
_img.height = toWidth/iWhp;
}
else {
_img.height = toHeight;
_img.width = toHeight*iWhp;
}
}
</script>
</html>





浙公网安备 33010602011771号