У меня есть следующий код, который перебирает элементы списка, заставляя их затухать в/из, он работает, но мне нужна помощь в добавлении предыдущей навигации, а также без дублирования кода.
HTML:
<ul id="site_slideshow_inner_text">
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
</ul>
Jquery
$(function () {
var list_slideshow = $("#site_slideshow_inner_text"),
listItems = list_slideshow.children('li'),
listLen = listItems.length,
i = 0,
changeList = function () {
listItems.eq(i).fadeOut(300, function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(300);
});
};
listItems.not(':first').hide();
setInterval(changeList, 1000);
});
Любая помощь будет оценена, спасибо.
Попробуйте сделать это более общим:
var
$listItems = $("#site_slideshow_inner_text").children('li'),
fadeDuration = 300,
interval;
$listItems.not(':first').hide();
function showSlide(elm) {
//fadeout the visible one and fade in the element passed to the function
$listItems.filter(':visible').fadeOut(fadeDuration, function () {
elm.fadeIn(fadeDuration);
});
}
function autoSlide() {
//auto slide is set up to go forward
interval = setInterval(function () {
showSlide( getNextElement('next'));
}, 1000);
}
$('#prev, #next').on('click', function () {
stopAutoSlide(); //stop auto slide
showSlide(getNextElement(this.id)); //Get next element by passing in prev/next as argument which are the id of the element itself.
});
//Here is the major section that does all the magic of selection the element
function getNextElement(direction) {
//Here direction will be prev or next they are methods on jquery to select the element, so it will select correspoding element by executing that specific function i.e next() or prev().
// Also set up a fallback if there is no element in next or prev you need to go to last or first and execute it.
var $next = $listItems.filter(':visible')[direction](),
fallBack = (direction === 'prev' ? 'last' : 'first');
return !$next.length ? $listItems[fallBack]() : $next;
}
function stopAutoSlide() {
$listItems.stop(true, true, true); //just clean up the animation queues
clearInterval(interval); //clear the interval
}
autoSlide(); //Kick off auto slide
Вы можете остановить автоматический цикл, создавая переменную типа var x = setInterval(changelist,1000);
Затем clearInterval(x);
Что касается предыдущего и следующего элементов управления, вы можете установить "следующий" щелчок на clearInterval, а затем вызвать функцию changeList(). Для prev вам нужно будет создать другую функцию, в которой вы вычитаете 1 из я и проверяете, если я === -1, установите ее в последний элемент.
См. Здесь: http://jsfiddle.net/upPp4/1
Чтобы остановить цикл, вы должны назначить setInterval переменной:
var myInt = setInterval(changeList, 1000);
а затем вызовите эту ручку с clearInterval:
clearInterval(myInt);
Затем снова вызовите свою функцию:
changeList();
Таким образом, ваш код кнопки будет выглядеть как (непроверенный):
<input id="next" type="button" value=">">
<input id="prev" type="button" value="<">
$('#next').click(function() {
clearInterval(myInt);
changeList;
});