jQuery实现左右切换焦点图

2020-05-16 18:44:21易采站长站整理

// localize the index for prettier code
var focusedIndex = $slider.prop('index');

// determine what slide is focused
var $focus = $slider.find('> *').eq(focusedIndex);

// grab the width of that focused slide
var widthDelta = $focus.outerWidth();

// if we clicked the next button we're moving to the left (negative values, so
// multiply by -1).
if ($anchor.hasClass('next'))
{
widthDelta *= -1;
}

focusedIndex += ($anchor.hasClass('next')) ? 1 : -1;

// check that the upcoming movement won't push the first element too far to the right
// leaving whitespace before the element
if ($slider.find('> *').eq(0).position().left + widthDelta > 0)
{
return true;
}

// check that the upcoming movement won't push the last element too far to the left
// leaving whitespace after the element
var $lastChild = $slider.find('> *').eq(-1)
if ($lastChild.position().left + widthDelta < $slider.outerWidth() - $lastChild.outerWidth() - 1)
{
return true;
}

// get all the child elements, so we can loop through them and detmine offsets based
// on widths
var $siblings = $slider.find('> *');

// finally loop through each child and kick off the animation
$siblings.each(function(index)
{
// we'll determine the `left` in just a second, sit tight
var left = 0;

// localize the child element
var $li = $(this);

// loop through each sibling and determine the new left
if (index < focusedIndex)
{
left = -$slider.outerWidth();
}

if (index >= focusedIndex && index < focusedIndex + 3)
{
left = 219 * (index - focusedIndex);
}

if (index >= focusedIndex + 3)
{
left = $slider.outerWidth() * 2;
}

// start the animation
$li.animate({'left': left}, 300);

// are we at the beginning?
if (index == 0 && left == 0)
{
$slider.prop('controls').find('.prev').addClass('disabled');
}
else if (index == 0)
{
$slider.prop('controls').find('.prev').removeClass('disabled');
}

// are we at the end?
if (index == $siblings.size()-1 && left == $slider.outerWidth() - $lastChild.outerWidth() - 1)
{
$slider.prop('controls').find('.next').addClass('disabled');
}
else if (index == $siblings.size()-1)
{
$slider.prop('controls').find('.next').removeClass('disabled');
}
});

// if we got down here then we actually moved the slider, update the reference to the
// focused slide
$slider.prop('index', focusedIndex);