jquery carousel - without a plugin

2019-04-14 04:46发布

问题:

I am wanting to rotate my divs with next and prev buttons. I know there are plugins etc available, but I want to do it myself, only I am not too sure how.

So here is the html markup that I have so far

<div class="prev-btn"></div>
<div class="row"> <!-- content in here --></div>
<div class="row"> <!-- content in here --></div>
<div class="row"> <!-- content in here --></div>
<div class="next-btn"></div>

What I want to do is display 1 row at a time, and when I click on the prev/next button, display a different div. When I am on the last row, next will display the first row again.

I know how to do onclick events and toggle a div. But I really don't know how to determine which row I am on and how to select the next one to display.

How can I get my next/prev buttons to work correctly?

回答1:

Just an idea of how you can do this..

var $rotator = $(".container");
$rotator.find("div .row:gt(0)").hide();

get div you want to show and the next div in the list

var $current = $rotator.find("div .row:visible");
var $next = $current.next();

Now on click of next do this,

if ($next.length == 0) 
   $next = $rotator.find("div .row:eq(0)");

$current.hide();
$next.show();

Similarly you can use .prev() to get previous sibling div.

Here is a simple Demo