js封装的一个menu,以备参考

function insertStyleSheet(styles, styleId) {
    if (!document.getElementById(styleId)) {
        var style = document.createElement("style");
        style.id = styleId;
        (document.getElementsByTagName("head")[0] || document.body).appendChild(style);
        if (style.styleSheet) { //for ie  
            style.styleSheet.cssText = styles;
        } else {//for w3c  
            style.appendChild(document.createTextNode(styles));
        }
    }
}
var menuList = [{
    label: 'Drag',
    selected:true,
    action: "menu_click(this,'Drag');",
    url:''
}, {
    label: 'Edit',
    action: "menu_click(this,'Edit');",
    url:''
}, {
    label: 'Add',
    action: "menu_click(this,'Add');",
    url:'',
    items: [{
        label: 'Image',
        action: "menu_click(this,'Image');",
        url:''
    }, {
        label: 'Text',
        action: "menu_click(this,'Text');",
        url:''
    }]
}];
function createMenu(id, list) {
    var styles=
  'ul{position:relative;margin:0;padding:0;height:32px;auto;}'
+ 'li {float:left;margin: 0;padding: 0;height: 32px; 60px;list-style:none;text-align:center;line-height:32px;position:relative;cursor:pointer;}'
+ 'li:hover {background-color:#eeeeee; }'
+ 'li ul {opacity:0;position:absolute;}'
+ '.menu_selected{background-color:#dddddd;}'
+ '.menu_spliter {  2px;height: 32px;background-color:#dddddd;}'
    insertStyleSheet(styles, "myMenuStyle");
    var ul = $('<ul></ul>');
    $('#' + id).append(ul);
    for (var i = 0; i < list.length; i++) {
        var menu = list[i];
        var li = $('<li name="' + menu.label + '">' + menu.label + '</li>');
        if (menu.items && menu.items.length > 0) {
            var cul = $('<ul></ul>');
            li.append(cul);
            for (var j = 0; j < menu.items.length; j++) {
                var child = menu.items[j];
                cul.append('<li name="' + child.label + '" onclick="' + child.action + '">' + child.label + '</li>');
            }
        } else {
            li.attr('onclick', menu.action);
        }
        ul.append(li);
        if (menu.selected) {
            li.addClass('menu_selected');
            ul.selected = li;
        }
        li.on('mouseenter', function () {
            var c = $(this).find("ul");
            if (c && c.css('opacity') == 0) {
                c.animate({ "opacity": "0.75", "height": "auto !important", "min-height": "80px" }, "slow", function () { })
            }
        }).on('mouseleave', function () {
            $(this).find("ul").animate({ "opacity": "0", "height": "0" });
        }).on('click', function () {
            ul.selected.removeClass('menu_selected');
            ul.selected = $(this).addClass('menu_selected');
        });
        if (i < (list.length - 1)) {
            ul.append('<li class="menu_spliter"></li>');
        }
    }
    return ul;
}

原文地址:https://www.cnblogs.com/foren/p/6009093.html