按比例显示缩略图,防止变形

本文介绍了两种实现图片自适应浏览器窗口大小的技术方案。一种是通过JavaScript动态调整图片大小以适应指定区域,确保图片按比例缩放;另一种是利用图片自身的onload事件结合JavaScript设置最大宽度和高度,保持图片原始宽高比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

<html>
<head>
<script language='javascript'>
function showImg1(smallWidth, smallHeight)
{
    document.all.image1.src 
= document.all.file1.value;
    
    var bigWidth 
= document.all.image1.width;
    var bigHeight 
= document.all.image1.height;
    var div1 
= bigWidth/bigHeight;
    var div2 
= bigHeight/bigWidth;

    var n1 
= 0;
    var n2 
= 0;
    
if(bigWidth>smallWidth)
    {
        n1 
= bigWidth/smallWidth;
    }
    
else
    {
        smallWidth 
= bigWidth;
    }
    
if(bigHeight>smallHeight)
    {
        n2 
= bigHeight/smallHeight;
    }
    
else
    {
        smallHeight 
= bigHeight;
    }
    
if(n1!=0 || n2!=0)
    {
        
if(n1>n2)
        {
            smallHeight 
= smallWidth*div2;
        }
        
else
        {
            smallWidth 
= smallHeight*div1;
        }
    }

    document.all.image2.width 
= smallWidth;
    document.all.image2.height 
= smallHeight;
    document.all.image2.src 
= document.all.file1.value;
}
</script>
</head>
<body>

<div id="div1">
      
<img id="image1">
</div>

<table border=1><tr><td width=100 height=100 align="center" valign="center">
    
<img id="image2" align="center">
</td></tr></table>

<form method="post" action="?action=get" action="">
<input type="file" id="file1" onpropertychange="showImg1(100, 100);"><br/>
</form>

</body>
</html>



<html>
<head>
<script language='javascript'>

function setImgSize(obj, defaultWidth, defaultHeight)
{
    var width 
= obj.width;
    var height 
= obj.height;
    
if(width>defaultWidth || height>defaultHeight)
    {
        
if(width>height)
        {
            obj.style.width 
= defaultWidth;
        }
        
else
        {
            obj.style.height 
= defaultHeight;
        }
    }
}

</script>
</head>
<body>

<img src="images/1.gif" border=0 onload="javascript:setImgSize(this, 100, 100)"><br/><br/>

</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值