【发布时间】:2012-03-05 05:16:15
【问题描述】:
这是一个简单的滑块代码,我想了解可变函数闭包是如何工作的......
(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(current === 0)块中,变量current、loc、direction是不是在第一个块中改变后更新了,然后传递给下面的transition函数?
我认为如果 else if ( current - 1 === imgsLen ) 为真,那么 current 和 loc 会覆盖之前分配给它们的值,然后传递给转换函数?
【问题讨论】:
标签: javascript jquery