图片自动适应容器大小的JS

来源:互联网 发布:json对象转字符串 编辑:程序博客网 时间:2024/05/02 09:18
$(window).load(function() {$("img[name='picautozoom']").each(function() {if (this.complete) {var smallWidth = $(this).width();var smallHeight = $(this).height();$(this).width(smallWidth).css("height", "auto");if ($(this).height() > smallHeight) {$(this).height(smallHeight).css("width", "auto");$(this).css("padding", "0px " + Math.floor(Math.abs((smallWidth - $(this).width()) / 2)) + "px");} else {$(this).css("padding", Math.floor(Math.abs((smallHeight - $(this).height()) / 2)) + "px 0px");}}});});


给图片属性name='picautozoom'  图片就会自动适应容器大小


js是在dom加载完成后,图片加载之前加载的。用$(document).ready(function(){//取得的图片宽带为0}); 所以要用$(window).load(function(){//取得的图片宽度为正常的宽度});

0 0