【发布时间】:2013-09-11 05:39:25
【问题描述】:
我正在尝试将容器的纵横比与一系列图像的纵横比进行比较,并为图像添加一个类纵向或横向。此外,我正在尝试根据定义的容差检测非常高/宽的图像(如大全景图)。我的基本功能可以正常工作here(前两张图片在左上角有一个“缩放”按钮)。
现在,我正在尝试拆分函数,因此当我调整页面大小时,脚本不会再次计算所有图像的比率 (var i_ratio),它只是将这些与新的容器比率 (var c_ratio)。我的开发示例是here。
我想我的问题是我不知道该怎么做:
- 确保第二个函数在第一个函数完成后运行
- 将 i_ratio 中的值从第一个函数传递到下一个函数
在开发示例中,有一个控制台日志显示 i_ratio 在第二个函数中未定义,但是当您调整窗口大小时,它似乎获得了一个值 - 不确定发生了什么。
// Get window aspect ratio
var container = $('.main');
var c_ratio = container.width() / container.height();
var i_ratio;
function imageRatios() {
// Get original dimensions of image (IE8+)
if (this.naturalWidth) {
i_width = this.naturalWidth;
i_height = this.naturalHeight;
} else {
// Get original dimensions of image with JQuery
i_width = this.width;
i_height = this.height;
}
i_ratio = i_width / i_height;
// Don't allow images to get bigger than their original size
$(this).css('max-width', i_width).css('max-height', i_height);
}
function setClass() {
console.log('number of images: '+images.length+', i_ratio from imageRatios function: '+i_ratio);
// Add ratio classes
if (c_ratio > i_ratio) {
$(this).parent('li').removeClass('landscape').addClass('portrait');
} else {
$(this).parent('li').removeClass('portrait').addClass('landscape');
}
// Identify long/tall panoramas and add zoom button
tolerance = c_ratio / i_ratio;
if (tolerance < 0.3 || tolerance > 5) {
$(this).after('<div class="zoom"></div>');
} else {
$(this).remove('.zoom');
}
// Show/hide zoomed image
var img = $(this);
$(this).next('.zoom').click(function() {
if (img.siblings('.big_image').size() > 0) {
$('.big_image').remove();
} else {
$(this).after('<div class="big_image"><img src="'+$img.attr('src')+'"></div>');
}
});
}
// Get images
var images = $('.main img');
images.each(function(i) {
if (this.complete) {
imageRatios.call(this);
setClass();
} else {
this.onload = imageRatios;
setClass();
}
});
// Update ratio class on resize
$(window).on("throttledresize", function() {
var c_ratio = container.width() / container.height();
images.each(function() {
setClass();
});
});
【问题讨论】:
-
请在您的问题中包含用于函数的javascript
-
相关代码已包含,谢谢。
-
好吧,你知道你可以将参数传递给函数吗?您似乎在使用全局变量在函数之间共享数据,这使您的代码不太灵活和易于理解。
-
@plalx 是的,我工作中的 js 人说我也应该先这样做,但是我尝试时一直打破它(我刚开始使用 jquery),你知道任何好的链接这解释了如何做到这一点?我在网上找不到任何东西,也许我在寻找错误的东西