将前四个列表项移到列表末尾 [英] Move the first four list items to the end of the list

查看:52
本文介绍了将前四个列表项移到列表末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个包含几个< li> 元素

So I have a list with several <li> elements,

<ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
    <li>f</li>
    <li>g</li>
    <li>h</li>
</ul>

上下文是我想在 iOS 的 1,000 个内存密集型列表中重用 li 元素.目的是显示前4个元素,其余4个元素被隐藏,容器一次显示4个项目.

The context is I want to re-use li elements across a 1,000 memory intensive list for iOS. The objective is to display first 4 elements, the rest 4 are hidden, the container displays 4 items at a time.

在滚动(点击按钮)时,我将对列表进行动画处理,然后滑动其他4个,然后在动画的末尾,将前4个 li 项移到末尾列表(然后将位置重新设置为 ul left:0 )

On scroll (button tap), I'm going to animate the list and slide in the other 4, and at the end of the animation, move the first 4 li items towards the end of the list (and then reset the position to left: 0 for the ul)

我的问题是如何获取第一批元素并将其添加到纯JavaScript末尾.(我正在通过TweenLite处理动画)

My question is how I can get a hold of first elements and add them towards the end in plain javascript. (I'm handling animation through TweenLite)

奖金::如果您可以建议一些更好的优化技术或库来显示大量元素,那么

Bonus: if you can suggest some better optimization techniques or library when it comes to display numerous elements.

推荐答案

在这里,您可以使用纯JS做到这一点.您可以使用 getElementsByTagName() 并使用 slice() 来获取前4个.然后您可以通过使用 shift() 和通过 appendChild()

Here's how you can do it in pure JS. You can access the li elements with getElementsByTagName() and use slice() to get the first 4. Then you can add them to the ul by popping them from the array with shift() and putting them on the end with appendChild()

在此使用JSFiddle.

function moveEle() {
    var ele = document.getElementsByTagName("li");
    //getElementsByTagName() returns a collection, so we bind the slice function to it
    var fourEle = Array.prototype.slice.call( ele, 0, 4);
    var ul = document.getElementsByTagName("ul")[0];

    while (fourEle.length > 0) {
        //Pop the first element from the 4 and add it to the end
        ul.appendChild(fourEle.shift());
    }
}

document.getElementById("clickMe").onclick = moveEle;

要在开头添加元素,请使用 insertBefore()而不是 appendChild().在上面的示例中,您还将使用 pop()而不是 shift().

To add an element at the beginning, use insertBefore() instead of appendChild(). You'd also use pop() instead of shift() in the above example.

这篇关于将前四个列表项移到列表末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆