我有一個函數,它根據某些條件調整圖像的大小,並希望它分別計算.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);