原創jQuery外掛程式之圖片自適應,jquery外掛程式自適應

來源:互聯網
上載者:User

原創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)


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.