4

当你add new点击按钮时,jQuery 会插入新dragrable DIVsCONTAINER. 当我单击其中一些时DIVs,我想更改z-index值。但是 jQuery 无法将 z-index 值作为数字获取。它只显示'auto'......是否有解决方案来显示真正的 z-index 值和increase it by 1

jsFiddle 示例 - http://jsfiddle.net/ynternet/84nVQ/10/

HTML

<div id="add" style="background:yellow; width:100px;"> add new </div>
<div id="container"> </div>

jQuery

function handler() {
    if ($(this).find("#menu").length) {
        return;
    }
    var currentIndex = $(this).css('z-index');
    alert(currentIndex);
    var newIndex = currentIndex + 1;
    alert(newIndex);
    $(this).css('z-index', newIndex);
}
$("#add").on({
    click: function(e) {
        var timestamp = Date.now();
        var posx = Math.floor(Math.random() * 400);
        var posy = Math.floor(Math.random() * 400);
        $('#container').append(function() {
            return $('<div class="add_to_this" id="' + timestamp + '" style="left:' + posx + 'px; top:' + posy + 'px; ">Click me, drag a change z-index</div>').click(handler).draggable({
                containment: "#container",
                scroll: false,
                cursor: 'lock'
        });
    });
    }
});

CSS

#container {
    width:500px;
    height:500px;
    background: palegoldenrod;
    position: relative;
    top:20px;
    left: 100px;
    padding: 0px;
}
.add_to_this {
    padding:5px;
    background:yellowgreen;
    position: absolute;
    display:inline-block;
    width:200px;
    height:50px;
    -moz-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    user-select: none;
    -o-user-select: none;
}
4

1 回答 1

5

Two problems in your code :

  • you don't have a real z-index to start with because you didn't set it, so you have 'auto'
  • you manipulate the z-index as string because you don't parse it

What you need to do :

  • add in the css a z-index : z-index:100;
  • parse the z-index : var currentIndex = parseInt($(this).css('z-index'), 10);

DEMONSTRATION (without the alerts as they were annoying)

于 2012-10-09T07:11:29.760 回答