How to change the z-index of list items in a menu

2019-04-12 17:12发布

问题:

I am making a long menu for a wordpress theme and it appears on two rows. The problem is that the sub menu of the top row appears under the list items on the bottom row. My solution is to change the z-index but I don't know how many elements the menu will have so I am using jQuery. Here is the code but it doesn't work. Could you help?

jQuery(document).ready(function ($) {
    var items;
    items=jQuery(".menu>ul>li").length;

    for (var i=0; i<items; i++){
        jQuery(".menu>ul>li").css("z-index", function( items, i ){
            return items - i;
        });
    }

},"jQuery");

回答1:

If you want to reverse the list, you can use:

var list = $('.menu>ul');
var items = list.children('li');
list.append(items .get().reverse());

This will reverse the order, so 1,2,3 becomes 3,2,1. z-index relates to the display order in terms of visual 'layering'.

The z-index CSS property specifies the z-order of an element and its descendants. When elements overlap, z-order determines which one covers the other. An element with a larger z-index generally covers an element with a lower one.

If you want to reverse z-index you can use:

var num= $('.menu>ul>li').length; /* or suitably high number depending on your layout */
$('.menu>ul>li').each(function(i, item) {
    $(item).css('z-index', num - i);
});