构建自定义CSS水平菜单

JavaScript to jQuery syntax Building custom CSS horizontal menu

本文关键字:菜单 水平 CSS 自定义 构建      更新时间:2023-09-26

这是一个使用传统JavaScript的水平菜单。

function createcssmenu()
{
    var ultags = document.getElementById("navmenu").getElementsByTagName("ul");
    for (var t = 0; t < ultags.length; t++)
    {
        ultags[t].style.top = ultags[t].parentNode.offsetHeight -1 + "px";
        ultags[t].parentNode.onmouseover = function()
        {
            this.style.zIndex = 100;
            this.getElementsByTagName("ul")[0].style.visibility = "visible";
            this.getElementsByTagName("ul")[0].style.zIndex = 0;
        }
        ultags[t].parentNode.onmouseout = function()
        {
            this.style.zIndex = 0;
            this.getElementsByTagName("ul")[0].style.visibility = "hidden";
            this.getElementsByTagName("ul")[0].style.zIndex = 100;
        }
    }
}
if (window.addEventListener)
    window.addEventListener("load", createcssmenu, false);
else if (window.attachEvent)
    window.attachEvent("onload", createcssmenu);

我需要使用jQuery语法重新编写。

where I came to:

$(document).ready(function ()
{
    $('#navmenu ul').css('top', $('#navmenu ul').parent().height() - 1 + "px");
    $('#navmenu ul').parent().bind('mouseover', function ()
    {
        $(this).css('z-index', 100);
        $('#navmenu ul').css({ 'visibility': 'visible', 'z-index': 0 });
    });
    $('#navmenu ul').parent().bind('mouseout', function ()
    {
        $(this).css('z-index', 0);
        $('#navmenu ul').css({ 'visibility': 'hidden', 'z-index': 100 });
    });
});

它不能正常工作。

我用this.getElementsByTagName("ul")[0]线还是有问题。

查看JSfiddle http://jsfiddle.net/sublay/HCajr/

它应该工作在一个正常的菜单。

谢谢!

相关问题JavaScript到jQuery语法转换

我想这就是你想要的。

$(document).ready(function ()
{
    $('#navmenu ul').css('top', $('#navmenu ul').parent().height() - 1 + "px");
    $('#navmenu ul').each(function(){
        $(this).css('top', $(this).parent().height() - 1 + "px")
    });
    $('#navmenu ul').parent().bind('mouseover', function ()
    {
        $(this).css('z-index', 100);
        $('ul',this).css({ 'visibility': 'visible', 'z-index': 0 });
    });
    $('#navmenu ul').parent().bind('mouseout', function ()
    {
        $(this).css('z-index', 0);
         $('ul',this).css({ 'visibility': 'hidden', 'z-index': 100 });
    });
});

与其尝试重写上面的javascript,不如简化它。

看看这个小提琴- http://jsfiddle.net/DeHQ5/

$(document).ready(function () {
    $('#navmenu ul').css('top', $('#navmenu ul').parent().height() - 1 + "px");
    $('#navmenu > li').bind('mouseover', function () {
        $(this).children('ul').css({
            'visibility': 'visible',
            'z-index': 0
        });
    });
    $('#navmenu > li').bind('mouseout', function () {
        $(this).children('ul').css({
            'visibility': 'hidden',
            'z-index': 100
        });
    });
});

主要的变化是初始的兄弟选择器#navmenu > li