2015-04-18 5 views
3

Я уже нашел решение для этого, но я новичок в JQuery.Перемещение по нескольким divs с помощью следующих и предыдущих кнопок

Как вы меняете его так, чтобы я мог показывать три div за раз, и когда нажимают на следующие или предыдущие кнопки, он выдвигает 1 вместо того, чтобы показывать только по одному.

Вот это JS Fiddle я смотрел на:

http://jsfiddle.net/TrueBlueAussie/aVJBY/468/

и это JQuery:

function updateItems(delta) 
{ 
    var $items = $('#group').children(); 
    var $current = $items.filter('.current'); 
    $current = $current.length ? $current : $items.first(); 
    var index = $current.index() + delta; 
    // Range check the new index 
    index = (index < 0) ? 0 : ((index > $items.length) ? $items.length : index); 
    $current.removeClass('current'); 
$current = $items.eq(index).addClass('current'); 
// Hide/show the next/prev 
$("#prev").toggle(!$current.is($items.first()));  
$("#next").toggle(!$current.is($items.last()));  
} 
$("#next").click(function() { 
updateItems(1); 
}); 
$("#prev").click(function() { 
updateItems(-1); 
}); 
// Cause initial selection 
updateItems(0); 

ответ

2

Вы можете сделать это таким образом, и это работает но, с другой стороны, я также уверен, что может быть более оптимизированный способ.

// give each div an id "#child1", "#child2", etc. 
$("#group div").each(function(i) { 
    $(this).attr('id', "child" + (i + 1)); 
}); 

var First = 1; 
var Second = 2; 
var Third = 3; 

$('#child'+First+', #child'+Second+', #child'+Third).addClass('current'); 

// on next click, add +1 to First, Second and Third 
$('#next').click(function(){ 
    if(!$('#child'+First).is(':last-child')) { 
     $("#group div").removeClass('current'); 
     First++; 
     Second++; 
     Third++; 
     $('#child'+First+', #child'+Second+', #child'+Third).addClass('current'); 
    } 
}); 

$('#prev').click(function(){ 
    if(!$('#child'+Third).is(':first-child')) { 
     $("#group div").removeClass('current'); 
     First--; 
     Second--; 
     Third--; 
     $('#child'+First+', #child'+Second+', #child'+Third).addClass('current'); 
    } 
}); 

Проверьте это здесь: http://jsfiddle.net/aVJBY/551/

редактировать: добавил if(!$('#child'+First).is(':last-child')) и if(!$('#child'+Third).is(':first-child')) таким образом, всегда есть по крайней мере, первый или последний div видимый

+0

Где являются Javascript герцогов прячешься? Конечно, есть решение менее чем в 10 строках кода! – Raoulito

+0

Я отредактировал скрипку: http://jsfiddle.net/aVJBY/552/ Таким образом, у вас всегда есть, по крайней мере, первый или последний div, видимый, они не могут скрыть. – Raoulito

0

вы можете дать каждый входной ДИВ идентификатор и с помощью JQuery купить щелканье следующий вас может получить, какой вход имеет активный класс и получить его id, а затем вы можете setfocuse следующий, добавив +1 к имени div и -1 setfoces, если вы хотите вернуться.

И помните, чтобы переместить имя класса соответственно

Вы можете использовать эти функции JQuery сделать это

var active_div = $(.active); 
$(P_active_div_id).removeClass("active"); 
$(N_active_div_id).addClass("active"); 
$("#target").focus(); 

Я надеюсь, что поможет

0

Попробуйте с использованием .slice()

var group = $("#group") 
 
, items = group.children().eq(0).addClass("current").addBack() 
 
, buttons = $("#next, #prev") 
 
, prev = buttons.filter("#prev").hide(0) 
 
, next = buttons.filter("#next"); 
 

 
buttons.on("click", function (e) { 
 
    var button = $(this) 
 
    , idx = function (index) { 
 
     return items.filter(".current").eq(index).index() 
 
    } 
 
    , _toggle = function (start, stop) { 
 
     $(".current").hide(0, function() { 
 
      $(this).removeClass("current"); 
 
      items.slice(start, stop) 
 
      .addClass("current").show(0); 
 
      prev.toggle(start > 0); 
 
      next.toggle(stop < items.length) 
 
     }) 
 
    }; 
 
    if (button.is(next) && idx(-1) + 4 <= items.length) { 
 
     _toggle(idx(-1) + 1, idx(-1) + 4) 
 
    } else if (button.is(prev) && idx(0) !== 0) { 
 
     _toggle(idx(0) === 1 ? 0 : idx(0) - 3, idx(0)) 
 
    }; 
 
});
#group div { 
 
    display: none; 
 
} 
 
#group div.current { 
 
    display: block; 
 
    border: 1px solid red; 
 
} 
 
#next, #prev { 
 
    width: 100px; 
 
    height 40px; 
 
    border: 1px solid blue; 
 
} 
 
#next { 
 
    float: right; 
 
} 
 
#prev { 
 
    float: left; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> 
 
</script> 
 
<div id="group"> 
 
    <div>one</div> 
 
    <div>two</div> 
 
    <div>three</div> 
 
    <div>four</div> 
 
    <div>five</div> 
 
    <div>six</div> 
 
    <div>seven</div> 
 
    <div>eight</div> 
 
    <div>nine</div> 
 
    <div>ten</div> 
 
</div> 
 
<div id="next">next</div> 
 
<div id="prev">prev</div>

jsfiddle http://jsfiddle.net/q1quarfk/

Смежные вопросы