0

ここに次のスクリプトがあります。の増加とともに、z-index をクリックします。しかし今、最後の要素を元の状態に復元したいと考えています。どういうわけか?

http://jsfiddle.net/dd5Wp/1/

$(function () {
    /*$("div.box").click(function() {
        console.log("start");

    })*/
    // Change this selector to find whatever your 'boxes' are
    var boxes = $("div.box");
    // Set up click handlers for each box
    boxes.click(function () {
        var el = $(this), // The box that was clicked
            max = 0;
        // Find the highest z-index
        boxes.each(function () {
            // Find the current z-index value
            var z = parseInt($(this).css("z-index"), 10);
            // Keep either the current max, or the current z-index, whichever is higher
            max = Math.max(max, z);
        });
        // Set the box that was clicked to the highest z-index plus one
        el.css("z-index", max + 1);
        /* hide and show the content*/
    });
});
4

2 に答える 2

0

私はちょうどあなたのケースに取り組み、最終的に解決策を見つけました.あなたのケースは実際にはピラミッド型のアプローチを必要としています. クリックされた要素はピラミッドの一番上の部分である必要があることを考慮してください。

このような:

     ----   Clicked element (Assume that it should have z-index 4) 
  ----  ----  (Assume that it should have z-index 3) 
 ----    ----  (Assume that it should have z-index 2)
----      ----  (Assume that it should have z-index 1) 

それを達成するために、左のピースを取得するためにprevAllを使用し、右のピースを取得するためにnextAllを使用しました。その後、それらをトラバースし、最上位の z-index からデクリメントして z-index を割り当てました。

$(function() {

    var boxes = $("div.box");
    var boxesLength = $("div.box").length;
    var count;

    boxes.click(function() {            

        var el = $(this);
        el.css("z-index", boxesLength);

        count = boxesLength -1;
        el.prevAll(".box").each(function(){
             $(this).css("z-index", count);
             count -= 1;
        });

        count = boxesLength -1;
        el.nextAll(".box").each(function(){
             $(this).css("z-index", count);
             count -= 1;
        });

    });
});

ライブ - デモ

于 2013-11-11T14:15:26.843 に答える
0

z-index私が正しく理解していれば、各画像は別の画像をクリックすると元に戻るはずです..

ここを見てください、多分それはあなたが必要とするものです:http://jsfiddle.net/dd5Wp/1/

コード

boxes.click(function() {
    var el = $(this), 
        max = 0;

    boxes.each(function() {

        //--- If a previous state is found, restore it
        if($(this).data("original-index")){
            $(this).css("z-index", $(this).data("original-index"));
        }
        var z = parseInt( $( this ).css( "z-index" ), 10 );
        max = Math.max( max, z );
    });

    //--- save the clicked element previous z-index
    el.data("original-index", el.css("z-index"));
    el.css("z-index", max + 1 );
});

PS:画像をラップするdiv(クリック動作を保持する)が画像自体よりも大きいため、「クリック動作」はうまく機能していません

于 2013-11-11T13:15:01.710 に答える