首页 > 解决方案 > 导航栏中选择菜单的定位

问题描述

我有一个定位菜单栏的要求,其中所有菜单项都相对于它们的位置放置。

喜欢:拳头选项将给予“所有野生动物”继续。现在在选择任何菜单项时,该项目将被放置在第一个位置,第一个选项将位于第二个位置,第一个项目“所有野生动物”将始终保持在第二个位置。

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' 保持不变。

标签: javascriptjquery

解决方案


我不确定是否允许您更改 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);
     });

推荐阅读