Я использую jQuery для динамического изменения позиции некоторых элементов. Я нашел что-то, что работает здесь: qaru.site/questions/93800/..., но если номер индекса выше, чем число детей, элемент выходит из родительского.
Есть ли способ заставить ребенка оставаться внутри родительского элемента?
CSS
#hook-header {
background: #dadada;
margin: 10px;
padding: 10px;
}
HTML
<header id="hook-header">
<div id="ImTheFirstElement"><h1>This is the header hook</h1></div>
</header>
<div id="example-one">01</div>
<div id="example-nintynine">99</div>
JQuery
$(document).ready(function () {
$('#example-one').appendTo('#hook-header');
$.fn.appendToIndex=function(to,index){
if(! to instanceof jQuery){
to=$(to);
};
if(index===0){
$(this).prependTo(to)
}else{
$(this).insertAfter(to.children().eq(index-1));
}
};
$('#ImTheFirstElement').appendToIndex($('#hook-header'),0)
$('#example-one').appendToIndex($('#hook-header'),1)
$('#example-nintynine').appendToIndex($('#hook-header'),99)
});
Измените плагин, чтобы использовать последний элемент, если eq(index)
не возвращает элемент
$(document).ready(function () {
$('#example-one').appendTo('#hook-header');
$.fn.appendToIndex=function(to,index){
if(! to instanceof jQuery){
to=$(to);
};
if(index===0){
$(this).prependTo(to)
}else{
var el = to.children().eq(index-1);
el = el.length ? el : to.children().last();
$(this).insertAfter(el);
}
};
$('#ImTheFirstElement').appendToIndex($('#hook-header'),0)
$('#example-one').appendToIndex($('#hook-header'),1)
$('#example-nintynine').appendToIndex($('#hook-header'),99)
});