[英]if the LI tag has a class of active it will go to the last position
I have multiple li
tag, if the user clicks one of those tags it will have a class
of active and then the li
tag will go to the end position of the list.我有多个
li
标签,如果用户点击这些标签中的一个,它将有一个活动class
,然后li
标签将转到列表的结束位置。 but if the user decided to click the li
tag it will remove the class and the li
tag will go back to the previous position.但是如果用户决定点击
li
标签,它将删除类并且li
标签将返回到之前的位置。
$(document).ready(function(){ $("button.move").on('click', function(){ $(".active").insertAfter("li:last-child()"); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="move">move</button> <ul> <li class="active">1st list item</li> <li>2nd list item</li> <li>3rd list item</li> </ul>
You could make your list flex
( or grid
as david mentions in the comments ) and use the order
property on the li
when you want to re-order them.您可以使您的列表
flex
(或grid
作为david在评论中提到的)并在您想要重新排序它们时使用li
上的order
属性。
So no real change is happening in the DOM, but the .active
element will be shown in the end.所以在 DOM 中没有发生真正的变化,但
.active
元素将在最后显示。
document.querySelector('ul').addEventListener('click', (e) => { const element = e.target; const isLI = element.nodeName === 'LI'; if (isLI) { element.classList.toggle('active'); removeClassFromSiblings(element, 'active'); } }) function removeClassFromSiblings(element, classname) { let prev = element; let next = element; // remove active from preceeding elements while (prev = prev.previousElementSibling) { prev.classList.remove('active'); } // remove active from following elements while (next = next.nextElementSibling) { next.classList.remove('active'); } }
ul { display: flex; /* or grid */ flex-direction: column; /* if using flex */ } .active { order: 1; color: red; }
<ul> <li>first</li> <li>second</li> <li>third</li> <li>fourth</li> <li>fifth</li> <ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.