jQuery 等比例縮放大圖片執行個體代碼

來源:互聯網
上載者:User

我們分兩種情況來講述:

1.已知圖片尺寸

 代碼如下 複製代碼

<div id="demo1"> 
    <img src="a.jpg" width="800" height="300" alt=""> 
</div> 


當頁面載入的圖片<img>中含有屬性width和height值,則可以使用幾句簡單的jQuery代碼實現等比例縮放。

 代碼如下 複製代碼

$(function(){ 
    var w = $("#demo1").width();//容器寬度 
    $("#demo1 img").each(function(){//如果有很多圖片,我們可以使用each()遍曆 
        var img_w = $(this).width();//圖片寬度 
        var img_h = $(this).height();//圖片高度 
        if(img_w>w){//如果圖片寬度超出容器寬度--要撐破了 
            var height = (w*img_h)/img_w; //高度等比縮放 
            $(this).css({"width":w,"height":height});//設定縮放後的寬度和高度 
        } 
    }); 
}); 

2.未知圖片尺寸

當頁面載入的圖片尺寸未知的情況下,上述代碼則不能進行有效縮放,這種情況多出現在採集的外部連結圖片。

 代碼如下 複製代碼

<div id="demo2"> 
    <img src="yun_qi_img/63826f14jw1e1w67g8tdfj.jpg" alt=""> 
</div> 

這樣的話我們jquery無法實現了,下面一個朋友寫了一個不錯的解決求知圖片等比例縮放效果

通過imgReady可以跨瀏覽器在dom ready就可以實現圖片自適應,無需等待img載入,代碼如下:
(3-17修複網友crossyou 指出的一處錯誤,並且新版本去掉了替換圖片)

 代碼如下 複製代碼

(function ($) {
  // 檢測是否支援css2.1 max-width屬性
 var isMaxWidth = 'maxWidth' in document.documentElement.style,
  // 檢測是否IE7瀏覽器
  isIE7 = !-[1,] && !('prototype' in Image) && isMaxWidth;
 
 $.fn.autoIMG = function () {
  var maxWidth = this.width();
  
  return this.find('img').each(function (i, img) {
   // 如果支援max-width屬性則使用此,否則使用下面方式
   if (isMaxWidth) return img.style.maxWidth = maxWidth + 'px';
   var src = img.src;
   
   // 隱藏原圖
   img.style.display = 'none';
   img.removeAttribute('src');
   
   // 擷取圖標題尺寸資料後立即調整圖片
   imgReady(src, function (width, height) {
    // 等比例縮小
    if (width > maxWidth) {
     height = maxWidth / width * height,
     width = maxWidth;
     img.style.width = width + 'px';
     img.style.height = height + 'px';
    };
    // 顯示原圖
    img.style.display = '';
    img.setAttribute('src', src);
   });
   
  });
 };
 
 // IE7縮放圖片會失真,採用私人屬性通過三次插值解決
 isIE7 && (function (c,d,s) {s=d.createElement('style');d.getElementsByTagName('head')[0].appendChild(s);s.styleSheet&&(s.styleSheet.cssText+=c)||s.appendChild(d.createTextNode(c))})('img {-ms-interpolation-mode:bicubic}',document);

 /**
  * 圖標題資料載入就緒事件

  * @param {String} 圖片路徑
  * @param {Function} 尺寸就緒 (參數1接收width; 參數2接收height)
  * @param {Function} 載入完畢 (可選. 參數1接收width; 參數2接收height)
  * @param {Function} 載入錯誤 (可選)
  */
 var imgReady = (function () {
  var list = [], intervalId = null,

  // 用來執行隊列
  tick = function () {
   var i = 0;
   for (; i < list.length; i++) {
    list[i].end ? list.splice(i--, 1) : list[i]();
   };
   !list.length && stop();
  },

  // 停止所有定時器隊列
  stop = function () {
   clearInterval(intervalId);
   intervalId = null;
  };

  return function (url, ready, load, error) {
   var check, width, height, newWidth, newHeight,
    img = new Image();
   
   img.src = url;

   // 如果圖片被緩衝,則直接返回快取資料
   if (img.complete) {
    ready(img.width, img.height);
    load && load(img.width, img.height);
    return;
   };
   
   // 檢測圖片大小的改變
   width = img.width;
   height = img.height;
   check = function () {
    newWidth = img.width;
    newHeight = img.height;
    if (newWidth !== width || newHeight !== height ||
     // 如果圖片已經在其他地方載入可使用面積檢測
     newWidth * newHeight > 1024
    ) {
     ready(newWidth, newHeight);
     check.end = true;
    };
   };
   check();
   
   // 載入錯誤後的事件
   img.onerror = function () {
    error && error();
    check.end = true;
    img = img.onload = img.onerror = null;
   };
   
   // 完全載入完畢的事件
   img.onload = function () {
    load && load(img.width, img.height);
    !check.end && check();
    // IE gif動畫會迴圈執行onload,置空onload即可
    img = img.onload = img.onerror = null;
   };

   // 排入佇列中定期執行
   if (!check.end) {
    list.push(check);
    // 無論何時只允許出現一個定時器,減少瀏覽器效能損耗
    if (intervalId === null) intervalId = setInterval(tick, 40);
   };
  };
 })();

})(jQuery);


調用方法

 代碼如下 複製代碼

調用示範:$(‘#demo p’).autoIMG()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.