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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-09 20:34:54

问题


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);
});


来源:https://stackoverflow.com/questions/22857359/how-to-change-the-z-index-of-list-items-in-a-menu-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!