图片不变形缩小显示

 1、代码示例

<!DOCTYPE html>
<html>
  <head>
   <meta charset="UTF-8">
   <title></title>
   <style type="text/css">
     /*设置外框大小并将图片居中显示*/
     .img-box{
      width: 350px;
      height: 250px;
      border: 1px solid gray;
      display: flex;
      justify-content: center;
      align-items: center;
     }
     .text-color {
      color: red;
     }
   </style>
  </head>
  <body>
    <h2 class="text-color">
      原图片
    </h2>
    <div class="">
      <img src="img/timg1.jpg"/>
    </div>
    <h2 class="text-color">
      比例缩小后的图片
    </h2>
    <div class="img-box">
      <div class="">
        <img src="img/timg1.jpg" onload="AutoSize(this,350,250)"/>
      </div>
    </div>
  </body>
  <script type="text/javascript">
    /*
     *@param {string} theImg    -- 	theImg:要放图片的img元素,onload调用函数时传参this
     *@param {number} maxWidth  --  maxHeight  :img元素的高度,像素(图片框 最大高度)
     *@param {number} maxHeight --  maxWidth:img元素的宽度,像素(图片框 最大宽度)
     *@email 3204836547@qq.com
     * */
    function AutoSize(theImg, maxWidth, maxHeight) {
      /*原图片原始地址(用于获取原图片的真实宽高,当<theImg>标签指定了宽、高时不受影响)*/
      var newImage = new Image(); 
      newImage.src = theImg.src;
      /*当图片比图片框小时不做任何改变 */
      if(newImage.width < maxWidth && newImage.height < maxHeight) {
        theImg.width = newImage.width;
        theImg.height = newImage.height;
      } else {
        /*当原图片宽高比例大于图片框宽高比例,则以框的宽为标准缩放,反之以框的高为标准缩放*/
        if((maxWidth / maxHeight) <= (newImage.width / newImage.height)) {
          /*原图片宽高比例大于图片框宽高比例时*/
          var widthAuto = ((maxWidth - 0.1) / maxWidth * 100).toString() + '%'; 
          theImg.setAttribute("width", widthAuto);
          theImg.height = maxWidth * (newImage.height / newImage.width);
        } else {
          /*原图片宽高比例小于图片框宽高比例时*/
          var widthAuto = ((maxHeight * (newImage.width / newImage.height) - 0.1) / maxWidth * 100).toString() + "%";
          theImg.setAttribute("width", widthAuto);
          theImg.height = maxHeight; 
        }
      }
    }		
  </script>
</html>

2、运行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值