下面是一個簡單的滑塊代碼,我想了解的變量函數閉包是如何工作的?功能的可調關閉
(function($) {
var sliderUL = $('div.slider').css('overflow', 'hidden').children('ul'),
imgs = sliderUL.find('img'),
imgWidth = imgs[0].width, // 600
imgsLen = imgs.length, // 4
current = 1,
totalImgsWidth = imgsLen * imgWidth; // 2400
$('#slider-nav').show().find('button').on('click', function() {
var direction = $(this).data('dir'),
loc = imgWidth; // 600
// update current value
**(direction === 'next') ? ++current : --current;
// if first image
if (current === 0) {
current = imgsLen;
loc = totalImgsWidth - imgWidth; // 2400 - 600 = 1800
direction = 'next';
} else if (current - 1 === imgsLen) { // Are we at end? Should we reset?
current = 1;
loc = 0;
}
transition(sliderUL, loc, direction);**
});
function transition(container, loc, direction) {
var unit; // -= +=
if (direction && loc !== 0) {
unit = (direction === 'next') ? '-=' : '+=';
}
container.animate({
'margin-left': unit ? (unit + loc) : loc
});
}
})(jQuery);
在這一部分:
$('#slider-nav').show().find('button').on('click', function() {
var direction = $(this).data('dir'),
loc = imgWidth; // 600
// update current value
(direction === 'next') ? ++current : --current;
// if first image
if (current === 0) {
current = imgsLen;
loc = totalImgsWidth - imgWidth; // 2400 - 600 = 1800
direction = 'next';
} else if (current - 1 === imgsLen) { // Are we at end? Should we reset?
current = 1;
loc = 0;
}
transition(sliderUL, loc, direction);
});
在if(當前=== 0)塊,變量current,loc和方向在第一個塊中被更改後更新,然後它們被傳遞到下面的轉換函數?
我認爲,如果else if(current - 1 === imgsLen)爲true,那麼current和loc會寫入先前分配給它們的值,然後傳遞給transitions函數?
謝謝,這澄清了很多。非常好的解釋! – nick 2012-03-04 18:16:40