原創jQuery外掛程式之圖片自適應,jquery外掛程式自適應
如下:
功能:使圖片自適應置中位於容器內
限制:容器需要給定大小
使用方法:
1、引入jQuery,然後引入fitimg外掛程式
2、給需要圖片自適應的容器固定寬高
3、header .account .img { width: 40px; height: 40px; margin: 5px 5px; float: left; }
4、添加data-src屬性
<div class="img" data-src ="/Images/avatar.jpg"></div>
這裡並沒有寫img標籤,外掛程式會自動產生img,把容器當成你想要呈現的圖片就可以了
5、調用
$(".img").fitimg('/Images/捕獲.png')括弧內為如果data-src指向的圖片載入失敗的替補圖片,如果該圖片也載入失敗,則該容器會清空容器內所有內容
原始碼:
(function ($){ $.fn.extend({ fitimg: function (errorimg) { $(this).each(function () { if ($(this).data('src')) { $(this).empty() var img = document.createElement('img') $(this).append($(img)) $(img).load(function () { var parent = $(this).parent() var pWidth = parent.width() var pHeight = parent.height() var oWidth = $(this).width() var oHeight = $(this).height() if (oWidth / pWidth > oHeight / pHeight) { $(this).height(pHeight) var nWidth = pHeight * oWidth / oHeight $(this).width(nWidth) $(this).css('margin-left', -(nWidth - pWidth) / 2) } else { $(this).width(pWidth) var nHeight = pWidth * oHeight / oWidth $(this).height(nHeight) $(this).css('margin-top', -(nHeight - pHeight) / 2) } parent.css('overflow', 'hidden') }).error(function () { if (errorimg) { $(this).parent().data('src', errorimg).fitimg() } else { $(this).parent().empty() } }) $(img).attr('src', $(this).data('src')) } }) return $(this) } })})(jQuery)
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。