如何在简单的jquery幻灯片代码中添加prev和next按钮

Omz*_*zep 2 html javascript jquery slideshow

jQuery从这个博客下面的幻灯片中找到了这个简单的代码.

http://leavesofcode.net/2012/08/17/simple-slideshow/

它完美地工作在这个项目我在工作,现在,在那里我可以调用与图像jQuery load()功能和幻灯片仍然有效.虽然我想在相同的代码中实现上一个和下一个按钮,如果可能的话.任何帮助将非常感激.请帮助谢谢.

这是代码:http://jsfiddle.net/mblase75/CRUJJ/

<script>
$(document).ready(function() {
    setInterval(function() {
        var $curr = $('.slideshow img:visible'), // should be the first image
            $next = ($curr.next().length) ? $curr.next() : $('.slideshow img').first();
            // if there isn't a next image, loop back to the first image
        $next.css('z-index',2).fadeIn('slow', function() { // move it to the top
            $curr.hide().css('z-index',0); // move this to the bottom
            $next.css('z-index',1);        // now move it to the middle
        });
    }, 6000); // milliseconds
});
</script>

<div class="slideshow">
    <img src="first-image.jpg" width="500" height="100" alt="first image">
    <img src="second-image.jpg" width="500" height="100" alt="second image">
    <img src="third-image.jpg" width="500" height="100" alt="third image">
    <img src="fourth-image.jpg" width="500" height="100" alt="fourth image">
</div>

<style>
.slideshow {
    position: relative; /* necessary to absolutely position the images inside */
    width: 500px; /* same as the images inside */
    height: 100px;
}
.slideshow img {
    position: absolute;
    display: none;
}
.slideshow img:first-child {
    display: block; /* overrides the previous style */
}
</style>
Run Code Online (Sandbox Code Playgroud)

cfs*_*cfs 6

您需要为getNext和getPrev创建函数,并将这些函数作为事件处理程序附加到要在幻灯片中向前和向后移动的元素.

我创建了一个公共转换函数,它由getNext和getPrev函数共享,以便可以共享转换代码.

在下面的示例中,单击下一个或上一个按钮将暂停幻灯片放映,但可以轻松更改它以继续自动转换.

工作演示

var interval = undefined;
$(document).ready(function () {
    interval = setInterval(getNext, 2000); // milliseconds
    $('#next').on('click', getNext);
    $('#prev').on('click', getPrev);
});

function getNext() {
    var $curr = $('.slideshow img:visible'),
        $next = ($curr.next().length) ? $curr.next() : $('.slideshow img').first();

    transition($curr, $next);
}

function getPrev() {
    var $curr = $('.slideshow img:visible'),
        $next = ($curr.prev().length) ? $curr.prev() : $('.slideshow img').last();
    transition($curr, $next);
}

function transition($curr, $next) {
    clearInterval(interval);

    $next.css('z-index', 2).fadeIn('slow', function () {
        $curr.hide().css('z-index', 0);
        $next.css('z-index', 1);
    });
}
Run Code Online (Sandbox Code Playgroud)