【发布时间】:2011-11-10 22:35:43
【问题描述】:
我有一个函数可以根据某些标准调整图像大小,并希望它单独计算 .z 类中的所有元素,然后返回它们。
使用.each 通过函数运行所有图像,但返回所有图像的相同尺寸。不知道我在哪里搞砸了......
测试站点在这里:
(还必须在图像完全调整大小之前解决淡入问题,但这将是另一个问题)
JavaScript:
jQuery(function($) {
$('.z').respond();
});
(function($){
$.fn.respond = function() {
/* initialize function on window load and resize */
$(document).ready(function() {
dimensions();
});
$(window).load(function() {
dimensions();
});
$(window).resize(function() {
dimensions();
});
/* declare affected elements */
var pic = this
/* set image's height or width depending on the browser window's size */
function dimensions() {
return pic.each(function() {
/* declare variables */
var browserWidth = $(window).width();
var imgRatio = pic.width() / pic.height()
var availableHeight = ($(window).height() - $('header').height() - $('footer').height() - 80)
var browserRatio = browserWidth / availableHeight
/* image sizing logic */
if (browserRatio >= imgRatio) {
if (browserWidth > 640) {
/* if the browser is landscape and bigger than mobile, set the image's height to fill the available space */
pic.height(availableHeight).width('auto');
//$('body').css('background', 'blue');
} else {
/* it's mobile */
pic.width(browserWidth - 40).height('auto');
//$('body').css('background', 'red');
}
} else {
/* if the browser is portrait, set the image's width to fill the page */
pic.width(browserWidth - 40).height('auto');
//$('body').css('background', 'green');
}
/* horizontally center content */
pic.css('margin-left', (browserWidth - pic.width())/2);
});
};
};
})( jQuery );
【问题讨论】:
标签: jquery class function dynamic each