使用jQuery将列表项移动到无序列表的顶部 [英] Move list item to top of unordered list using jQuery
问题描述
让我们说我有以下无序列表
Lets say i have the following unordered list
<ul>
<li><a>Hank</a></li>
<li><a>Alice</a></li>
<li><a>Tom</a></li>
<li><a>Ashlee</a></li>
</ul>
我要寻找的是当我单击Tom时,它将移动(动画且不拖动)到列表顶部(索引0).
What im looking for is when i click on Tom, that it moves (animated and without dragging) to the top of the list (index 0).
我认为jquery是可排序的,但我找不到找到以编程方式激活运动部件的方法.
Ive considered jquery sortable, but i cant find a way to activate the moving part programmatically.
推荐答案
我想出了一个效果很好的解决方案.这是一个概念证明,因此您可能必须对其进行一些修改才能更好地适合您的特定情况.另外,我仅在Firefox中对其进行了测试,但是我看不出任何原因在所有浏览器中均无法正常运行.无论如何,这里是:
I came up with a solution that seems to work pretty well. It's a proof of concept, so you'll probably have to modify it a bit to work better for your specific case. Also, I only tested it in Firefox, but I don't see any reason why this wouldn't work in all the browsers. Anyway, here it is:
<script type="text/javascript">
$(document).ready(function() {
$('li').click(function() {
// the clicked LI
var clicked = $(this);
// all the LIs above the clicked one
var previousAll = clicked.prevAll();
// only proceed if it's not already on top (no previous siblings)
if(previousAll.length > 0) {
// top LI
var top = $(previousAll[previousAll.length - 1]);
// immediately previous LI
var previous = $(previousAll[0]);
// how far up do we need to move the clicked LI?
var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
// how far down do we need to move the previous siblings?
var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
// let's move stuff
clicked.css('position', 'relative');
previousAll.css('position', 'relative');
clicked.animate({'top': -moveUp});
previousAll.animate({'top': moveDown}, {complete: function() {
// rearrange the DOM and restore positioning when we're done moving
clicked.parent().prepend(clicked);
clicked.css({'position': 'static', 'top': 0});
previousAll.css({'position': 'static', 'top': 0});
}});
}
});
});
</script>
<ul>
<li><a>Hank</a></li>
<li><a>Alice</a></li>
<li><a>Tom</a></li>
<li><a>Ashlee</a></li>
</ul>
它计算被单击的LI
与第一个LI
之间的偏移量差,并将被单击的position
设置为relative
并为top
属性设置动画,从而将被单击的LI
移到顶部.同样,它计算单击的LI
留下了多少空间,并相应地向下移动所有先前的空间.完成动画处理后,它会重新排列DOM以匹配新的顺序并恢复定位样式.
It calculates the difference in offsets between the clicked LI
and first LI
and moves the clicked one up to the top by setting its position
to relative
and animating the top
property. Similarly, it calculates how much space was left behind by the clicked LI
and moves all the previous ones down accordingly. When it's done with the animations, it rearranges the DOM to match the new order and restores the positioning styles.
希望有帮助!
这篇关于使用jQuery将列表项移动到无序列表的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!