zoukankan      html  css  js  c++  java
  • js 完成对图片的等比例缩放的方法

     1 /*
     2     重新按比例设置 页面上对应图片的长和高,
     3  */
     4 function resetImgSize(id,imgWidth,imgHeight,posWidth,posHeight) {
     5     var width = 0;
     6     var height = 0;
     7     // 按比例缩小图片的算法
     8     if(imgWidth > imgHeight) {
     9         if(imgWidth > posWidth) {
    10             width = posWidth;
    11             height = imgHeight/imgWidth * width;
    12             
    13         }else {
    14             width = imgWidth;
    15             height = imgHeight;
    16         }
    17     }else {
    18         if(imgHeight > posHeight) {
    19             height = posHeight;
    20             width = (imgWidth/imgHeight) * height;
    21         }else {
    22             width = imgWidth;
    23             height = imgHeight;
    24         }
    25     }
    26     width = Math.floor(width);
    27     height = Math.floor(height);
    28     $('#'+id).attr('width',width);
    29     $('#'+id).attr('height',height);
    30     $('#'+id).css('padding-left',(posWidth-width)/2);
    31     $('#'+id).css('padding-top',(posHeight-height)/2);
    32 
    33 }
    34 
    35 /*
    36     获取图片尺寸
    37     imgURL  图片加载地址
    38     posId   图片位置id
    39     posWidth 放在图片位置的width
    40     posHeight 放在图片位置的height
    41  */
    42 
    43 function getImgSize(imgURL,posId,posWidth,posHeight) {
    44 
    45     var img = new Image();
    46      
    47 
    48     img.src = imgURL+'?'+Math.random();
    49     var width = 0;
    50     var height = 0;
    51     
    52 
    53     var check = function(){
    54 
    55         if(img.width > 0) {
    56 
    57         clearInterval(set);
    58         
    59         resetImgSize(posId,img.width,img.height,posWidth,posHeight);
    60         }
    61     };
    62      
    63     var set = setInterval(check,40);
    64 
    65     img.onload = function(){
    66         
    67         clearInterval(set);
    68     };
    69 
    70     
    71 }
    72 
    73 $(function(){
    74     $('.resetsize').each(function(){
    75         getImgSize(this.src,this.id,168,168);
    76     });
    77 });
  • 相关阅读:
    乒乓球运动中两种最基本的握拍方法
    Google 的 OKR 制度与KPI 有什么不同?
    推荐物品时,为了消除个人特殊癖好,或者未打分的情况,可通过加权计算进行修正
    甘特图
    解耦、异步、削峰 消息队列
    供给侧
    货币化 经济货币化 信用 经济金融化
    新浪广告交易平台(SAX)DSP手册
    SU suspike命令学习
    SU Demos-02Filtering-02Subfilt
  • 原文地址:https://www.cnblogs.com/wxb0328/p/4158235.html
Copyright © 2011-2022 走看看