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

版权声明:本文为博主原创文章,未经博主允许不得转载。

,快乐要有悲伤作陪,雨过应该就有天晴。

原创jQuery插件之图片自适应

相关文章:

你感兴趣的文章:

标签云: