我尝试搜索,但找不到我要找的东西。希望这对某人来说非常简单。
这是我开始的代码,我想将其转换为函数。显然有一种方法可以做到这一点,所以我不必重复。
var fullWidth = $('.full-img').width();
var paddBottom = fullWidth * .75;
$('.full-img').css('padding-bottom', paddBottom);
var thumbWidth = $('.img-box').width();
var thumbBottom = thumbWidth * .75;
$('.img-box').css('padding-bottom', thumbBottom);
这是我尝试过的
function aspectRatioFix(main, thumb) {
var fullWidth = main.width();
var paddBottom = fullWidth * .75;
main.css('padding-bottom', paddBottom);
var thumbWidth = thumb.width();
var thumbBottom = thumbWidth * .75;
thumb.css('padding-bottom', thumbBottom);
}
aspectRatioFix('.full-img', '.img-box');
我收到错误“Uncaught TypeError: main.width is not a function”
有没有办法可以循环遍历我的函数来处理脚本的两个部分,而不是仅仅复制我所拥有的内容? 谢谢!
最佳答案
函数 aspectRatioFix
需要 jQuery 对象,因此您必须传入 jQuery 对象而不是像这样的选择器(字符串):
aspectRatioFix($('.full-img'), $('.img-box'));
如果您有许多图像及其缩略图,并且想要为所有图像应用代码,请使用 .each
,如下所示:
var $mains = $('.full-img'),
$thumbs = $('.img-box');
$mains.each(function(index) {
// this: is the main image
// index: is its index so we can access the according thumb from $thumbs
aspectRatioFix($(this), $($thumbs[index])); // apply the aspectRatioFix on this main image, and on it's thumb from the $thumbs object (both this and $thumbs[index] are node elements so we have to wrap them in a jQuery object using $())
});
关于javascript - 如何将 jquery 选择传递到函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283973/