单击时更改列表项的位置

时间:2015-04-01 00:48:07

标签: javascript

什么算法可以解决以下问题?我需要当你点击其中一个菜单块时收到类活动并在中间站起来。

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li class="active">4</li>
    <li>5</li>
</ul>

ul li {
    float: left;
    list-style: none;
    background: red;
    margin-left: 20px;
    display: block;
    padding: 20px;
}

.active {
    background: orange;
}

Fiddle

1 个答案:

答案 0 :(得分:1)

要添加活动类,请执行以下操作

var liElems = document.getElementsByTagName('li'), mid = Math.floor(liElems.length/2);
Array.prototype.forEach.call(liElems, function (item, idx) {
    item.idx = idx;
    item.onclick = function () {
        document.querySelector('li.active').classList.remove('active');
        this.classList.add('active');
    };
});

演示:Fiddle


var liElems = document.getElementsByTagName('li'),
    length = liElems.length,
    mid = Math.floor(liElems.length / 2);
Array.prototype.forEach.call(liElems, function (item, idx) {
    item.idx = idx;
    item.onclick = function () {
        document.querySelector('li.active').classList.remove('active');
        this.classList.add('active');


        if (liElems[mid].idx != mid) {
            if (liElems[mid].idx == length - 1) {
                this.parentNode.appendChild(liElems[mid])
            } else {
                this.parentNode.insertBefore(liElems[mid], liElems[liElems[mid].idx])
            }
        }

        var pos = mid < this.idx ? mid : mid + 1;
        this.parentNode.insertBefore(this, liElems[pos])

    };
});

演示:Fiddle