javascript - 导航栏中选择菜单的定位
问题描述
我有一个定位菜单栏的要求,其中所有菜单项都相对于它们的位置放置。
喜欢:拳头选项将给予“所有野生动物”继续。现在在选择任何菜单项时,该项目将被放置在第一个位置,第一个选项将位于第二个位置,第一个项目“所有野生动物”将始终保持在第二个位置。
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);
});
推荐阅读
- django - DJANGO:网页的 URL 和媒体文件之间的混合问题
- javascript - Javascript过滤方法,删除数组中所有匹配值的项目
- c# - 添加“跳过”会引发异常:“跳过”方法仅支持 LINQ to Entities 中的排序输入
- android - 存储要对对象打开的活动
- firebase - 使用数组还是子集合?
- scale - 如何在保持垂直笔划宽度相同(并且不改变任何水平尺寸)的同时垂直缩小字形?
- python - 二叉树如何在水中工作?
- html - 如何使用 css 网格构建 Web 模板,使其成为这样?
- firebase - 可重新排序的大型数组的最佳 NoSQL 服务器结构
- assembly - RISC-V ISA 中的任何假设阻止堆栈增长而不是下降?