частичное изменение списка элементов с помощью jQuery - PullRequest
0 голосов
/ 19 января 2012

Я делаю счеты с 10 бусами. При щелчке по бусинке этот шарик и все шарики перед его размещением остаются в абаках, а остальные шарики перемещаются вправо в абаках.

Список:

<ul class="abacus">
    <li class="bead">1</li>
    <li class="bead">2</li>
    <li class="bead">3</li>
    <li class="bead">4</li>
    <li class="bead">5</li>
    <li class="bead">6</li>
    <li class="bead selected">7</li>
    <li class="bead off">8</li>
    <li class="bead off">9</li>
    <li class="bead off">10</li>
</ul>

CSS:

li.bead {
    cursor: pointer;
    width: 28px;
    height: 32px;
    float: left;
}

/* just for visuals: */
li.bead.selected {
    background-image: url('../images/smartie-selected.png');
}

li.bead.off {
    float: right;
    background-image: url('../images/smartie-unselect.png');
}

Поскольку «выключенные» шарики плавают вправо, их порядок должен быть обратным (в противном случае счеты будут выглядеть следующим образом: [1] [2] [3] [4] [5] [6] [7] -------- [10] [9] [8]).

JQuery, который я использую для этого:

$("li.bead").click(function() {
    // remove the 'selected' class of the previously selected bead (just for visuals):
    $("li.bead.selected").removeClass("selected");

    // save the number of the bead was selected:
    var no = Number($(this).html());

    // add the 'selected' class to the clicked bead (just for visuals):
    $(this).addClass("selected");

    // add the 'off' class to all the 'higher' beads than the selected one 
    // and removing that class for all he lower beads:
    $(this).parent().children().each(function() {
        if(Number($(this).html()) > no) {
            $(this).addClass('off');
        } else {
            $(this).removeClass('off');
        }
    });

    // reverse all beads:
    $(this).parent().children().each(function(i, li) {
        $(this).parent().prepend(li);
    });             
});

Итак, последний шаг в этом jQuery переворачивает все бусинки, что правильно расставляет «бусинки», но также переворачивает другие бусинки, делая, например, счеты:

[4] [3] [2] [1] ------------ [5] [6] [7] [8] [9] [10] * * 1016

Что мне добавить, чтобы перевернуть только первые бусы?

Ответы [ 3 ]

4 голосов
/ 19 января 2012

Я бы хотел избежать плавания. Сначала я бы попытался добавить значение margin-right для выбранного элемента. Как то так ...

$("li.bead").click(function() {
    // remove the 'selected' class of the previously selected bead (just for visuals):
    $("li.bead.selected").removeClass("selected");
    $("li.bead.off").removeClass("off");

    // save the number of the bead was selected:
    var no = Number($(this).html());

    // add the 'selected' class to the clicked bead (just for visuals):
    $(this).addClass("selected");

    // add the 'off' class to all the 'higher' beads than the selected one
    $(this).nextAll().addClass("off");         
});

и CSS ...

li.bead {
    cursor: pointer;
    width: 28px;
    height: 32px;
    float: left;
}

/* just for visuals: */
li.bead.selected {
    margin-right:100px;/*change this to suit your design*/
    background-image: url('../images/smartie-selected.png');
}

li.bead.off {
    background-image: url('../images/smartie-unselect.png');
}

Вот рабочий пример

если вам нужно, чтобы правое поле было динамичным, вы всегда можете рассчитать его в javascript и добавить к выбранному элементу, что-то вроде ...

var parent = $(this).parent();
var margin = parent .width() - (parent.children().length * $(this).width());
parent.children().css("margin-right", "0px");//clear other margins
$(this).css("margin-right", margin + "px");//set this margin
1 голос
/ 19 января 2012

Вы должны были бы создать пример, я никогда не использовал счеты (я не такой уж старый!), И я не могу сказать, что я действительно понимаю, в чем проблема.Но, думаю, я бы посоветовал взглянуть на методы jquery

nextAll()
prevAll()

, поскольку это позволит вам указывать только шарики ПОСЛЕ или ДО выбранного шарика ... что, я считаю, то, что вам нужно сделать

0 голосов
/ 19 января 2012

Как насчет этого?

$(this).parent().children().each(function() {
        if(Number($(this).html()) > no) {
            $(this).addClass('off');
            $(this).parent().prepend(li);

        } else {
            $(this).removeClass('off');
            $(this).parent().append(li);

        }
    });
...