Tạo slideshow đơn giản với jQuery phần 2
Ở phần tiếp theo này tôi muốn hướng dẫn các bạn thêm nút Previous và Next vào sildeshow.

Mã HTML không có gì thay đổi so với bài hướng dẫn tạo slideshow đơn giản với jQuery. Mã CSS được thêm style cho nút previous và next như sau:
.neoslideshow {position:relative; width:500px; height:260px;} .neoslideshow img {position:absolute;left:0; top:0; z-index:10} #galprev, #galnext {position: absolute; z-index:20; top: 125px; cursor: pointer; background: #000; color: #fff; width: 28px; height: 20px; line-height: 20px; text-align: center} #galprev {left: 0;} #galnext {right: 0}
Ở phần xử lý của javascript, tạm thời chúng ta sẽ không cho slideshow chạy tự động và code javascript như sau:
$(function() { var $galitem = $('.neoslideshow').children(); // Đếm các ảnh trong gallery var $galsize = $('.neoslideshow img').size(); // Thêm nút Prev và Next vào gallery $('.neoslideshow').append('<div id="galprev">Prev</div><div id="galnext">Next</div>'); // Ẩn tất cả các ảnh và hiện ảnh đầu tiên $('.neoslideshow img:gt(0)').hide(); $currentimg = 0; // Thêm id để phân biệt riêng từng ảnh $galitem.attr("id", function (arr) { return "galleryitem" + arr; }); // Thêm sự kiện click vào nút Prev $('#galprev').click(function () { if ($currentimg > 0) { previmg($currentimg); $currentimg = $currentimg - 1; } }); // Thêm sự kiện click vào nút Next $('#galnext').click(function () { if ($currentimg < $galsize - 1) { nextimg($currentimg, $galsize); $currentimg = $currentimg + 1; } }); }) // Hàm xử lý khi nút Next được ấn function nextimg($img, $size) { $n_img = $img + 1; if ($n_img < $size) { $('#galleryitem' + $img).fadeOut(); $('#galleryitem' + $n_img).fadeIn(); } } // Hàm xử lý khi nút Previous được ấn function previmg($img) { $p_img = $img - 1; if ($p_img >= 0) { $('#galleryitem' + $img).fadeOut(); $('#galleryitem' + $p_img).fadeIn(); } }
Tới đây slideshow đơn giản đã bắt đầu không đơn giản nữa, bạn muốn có chức năng gì ở slideshow trong phần tiếp theo?