我有一个函数,它根据某些条件调整图像的大小,并希望它分别计算.z
类中的所有元素,然后返回它们。在类中的每个元素上运行jQuery函数
使用.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);