jQuery實現圖片尺寸自適應效果

antzone發表於2017-04-12

本章節分享一段程式碼例項,它實現了圖片尺寸自適應效果。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.box {
  width: 960px;
  height: 700px;
  margin: 0 auto;
  padding: 10px;
  border: 10px solid orangered;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(document).ready(function () {
  var _w = parseInt($(".box").width());
  $(".box img").each(function (i) {
    var img = $(this);
    var realWidth;
    var realHeight;
    $("<img/>").attr("src", $(img).attr("src")).load(function () {
      realWidth = this.width;
      realHeight = this.height;
      if (realWidth >= _w) {
        $(img).css("width", "100%").css("height", "auto");
      }
      else {
        $(img).css("width", realWidth + 'px').css("height", realHeight + 'px');
      }
    });
  });
})
</script>
</head>
<body>
<div class="box"><img src="img/2.jpg"/></div>
</body>
</html>

上面的程式碼實現了我們的要求,下面介紹一下它的實現過程。

一.程式碼註釋:

(1).$(document).ready(function () {}),當文件結構載入完畢再去執行函式中的程式碼。

(2).var _w = parseInt($(".box").width()),獲取容器的寬度。

(3).$(".box img").each(function (i) {}),遍歷每一個img元素。

(4).var img = $(this),獲取img元素物件。

(5).var realWidth,用來儲存圖片的真實寬度。

(6).var realHeight,用來儲存圖片的真實高度。

(7).$("<img/>").attr("src", $(img).attr("src")).load(function () {}),建立一個img元素物件,並且將其src屬性賦值為img標籤的src屬性值,然後註冊load事件處理函式,也就是圖片載入完成就會觸發此事件。

(8).if (realWidth >= _w) {

  $(img).css("width", "100%").css("height", "auto");

}

else {

  $(img).css("width", realWidth + 'px').css("height", realHeight + 'px');

},通過實際寬度與容器寬度的比較,設定圖片的width屬性值和height屬性值。

二.相關閱讀:

(1).parseInt()可以參閱javascript parseInt()一章節。

(2).attr()可以參閱jQuery attr()方法一章節。

相關文章