更改z-index以使单击的div显示在顶部

hol*_*ard 11 css jquery z-index

在我的应用程序中,我可以打开几个相互重叠的div框.单击框时应将该框移动到顶部.完成此任务的最佳方法是什么?

我唯一能想到的是循环遍历所有框z-index值以获得最高值,然后将1加到该值并将其应用于单击的div.

对我有什么建议吗?

kee*_*ins 14

这样的事情应该这样做:

// Set up on DOM-ready
$(function() {
    // Change this selector to find whatever your 'boxes' are
    var boxes = $("div");

    // 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 );
    });
});
Run Code Online (Sandbox Code Playgroud)


Erw*_*wan 5

假设你有一个特定类的元素(在我的例子中为"box"),并且所有元素都在同一容器中,如下所示:

<div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

假设你有正确的CSS:

.box {position:absolute; z-index:10}
Run Code Online (Sandbox Code Playgroud)

您可以使用下面的jquery js代码:

$('.box').click(function() {
   // set ohters element to the initial level
   $(this).siblings('.box').css('z-index', 10);
   // set clicked element to a higher level
   $(this).css('z-index', 11);
});
Run Code Online (Sandbox Code Playgroud)