Image self-adaptation of original jQuery plug-ins
As follows:
Function:Make the image adaptive center in the container
Restrictions:Container size needs to be specified
Usage:
1. Introduce jQuery, and then introduce the fitimg plug-in.
2. fixed width and height for containers requiring adaptive Images
3、header .account .img { width: 40px; height: 40px; margin: 5px 5px; float: left; }
4. Add the data-src attribute
The img tag is not written here. The plug-in will automatically generate the img and use the container as the image you want to render.
5. Call
$ (. Img). fitimg ('/Images/catch .png ')
The brackets indicate the backup image that fails to be loaded if data-src points to the image. If the image fails to be loaded, the container clears all content in the container.
Source code:
(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)