As follows:
function: make the picture adaptive centered in the container
limit: container needs a given size
How to use:
1, introduce jquery, then introduce fitimg plug-in
2, to the need to adapt the image of the container fixed width high
3. Header. Account. img {width:40px; height:40px; margin:5px 5px; float:left;}
4. Add Data-src Property
<div class= "img" DATA-SRC = "/images/avatar.jpg" ></div>
This does not write an IMG tag, the plugin will automatically generate IMG, the container as you want to render the picture on it
5. Call
$ (". img"). FITIMG ('/images/capture. png ')
In parentheses, if the picture that the data-src points to fails to load, if the picture also fails to load, the container empties everything inside the container
Source:
(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)
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Original jquery plugin Image adaptive