我有这样的要求:将菜单栏放置在相对于其位置放置所有菜单项的位置。
例如:拳头选项将授予“所有WildLife”继续进行。现在,在选择任何菜单项时,该菜单项将放置在第一位置,第二个选项将显示在第二个位置,第一个选项“ All Wildlife”将始终位于第二个位置。
HTML:
`<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='subpage_top_nav'>
<ul>
<li>
<a href='#'>
<center>All WildLife</center>
</a>
</li>
<li>
<a href='#'>
<center>Kavango</center>
</a>
</li>
<li>
<a href='#'>
<center>Northeast Greenland</center>
</a>
</li>
<li>
<a href='#'>
<center>Pacific Remote</center>
</a>
</li>
<li>
<a href='#'>
<center>Papahānaumokuākea </center>
</a>
</li>
</ul>
</div>`
JS:
$('.subpage_top_nav li').click(function(e) {
e.preventDefault();
$(this).parent().prepend(this);
});
我能够通过以上逻辑实现这一目标。我想将活动菜单放回选择其他菜单之前的位置。
案例:页面渲染菜单如下:1.所有野生动物2.卡万戈3.东北格陵兰4.太平洋遥控器5.Papahānaumokuākea
情况1:如果单击'Pacific Remote'->'Pacific Remote'转到第一位置,'All WildLife'转到第二位置。
案例2:单击'Papahānaumokuākea'->'Pacific Remote'回到第4位,'Papahānaumokuākea'首先出现,'All WildLife'保持不变。
[我不确定是否允许您更改html,所以我只使用js,如果可以,请将索引添加到html中,您可以将js减少一半
以“冗长”的方式完成,希望您能理解这些步骤
$('.subpage_top_nav li').click(function(e) {
e.preventDefault();
/* find the element that needs to be moved */
var $toBeMoved = $('.need-to-go-back')
/* check if any1 actually needs to be moved */
if($toBeMoved) {
/* grab his init position */
var initPosition = $toBeMoved.attr('initial-position')
/* move the element there */
$('.subpage_top_nav li:eq(' + initPosition + ')').after($toBeMoved)
/* remove the signaling class */
$toBeMoved.removeClass('need-to-go-back')
/* remove the attr */
$toBeMoved.removeAttr('initial-position')
}
/* grab index */
var index = $(this).index()
/* save original index to know where it should be placed */
$(this).attr('initial-position', index)
/* add signaling class just to be easier to find it later */
$(this).addClass('need-to-go-back')
$(this).parent().prepend(this);
});