使用li <a> with jquery

时间:2015-11-30 22:55:26

标签: jquery css

I am coding a dropdown submenu as below:

<ul id="main_menu">
    <li class="enter-top-level">
        <a href="#entering">
            Enter Data
            <ul id="enter_scheme_global">
                <li class='submenu'>
                    <a href="#enter_scheme">
                        Scheme Details
                    </a>
                </li>
                <li class='submenu'>
                    <a href="#enter_transformer">
                        Transformer
                    </a>
                </li>
                <li class='submenu'>
                    <a href="#enter_AIS">
                        AIS
                    </a>
                </li>
                <li class='submenu'>
                    <a href="#enter_GIS">
                        GIS
                    </a>
                </li>
            </ul>
        </a>
    </li>

I want to give it a animated slideDown and slideUp effect with jquery and I tried the following :

$('a').mouseenter(function() {
    $(this).find('ul').slideToggle(500);
    $(this).parent('.submenu').css({"background-color" : "#700000"});
});//end $('a').hover function*/

$('a').mouseout(function() {
    $(this).find('ul').fadeToggle(500);
    $(this).parent('.submenu').css({"background-color" : "#C8C8C8"});
});//end $('a').hover function*/

but without success. Any help anybody.

2 个答案:

答案 0 :(得分:1)

代码有几个问题。

首先,您的HTML需要更改。您的顶级a标记会包含所有元素,这会导致子a元素无效。您也不需要为mouseover/mouseout提供两个单独的函数。您可以使用hover()方法。此外,定位父li将允许菜单保持打开状态,因为鼠标仍在其上(而不是a元素)。这是工作代码:

小提琴: http://jsfiddle.net/xf02743m/1/

HTML

<ul id="main_menu">
    <li class="enter-top-level"><a href="#entering">Enter Data</a>

        <ul id="enter_scheme_global">
            <li class='submenu'><a href="#enter_scheme">Scheme Details</a>

            </li>
            <li class='submenu'><a href="#enter_transformer">Transformer</a>

            </li>
            <li class='submenu'><a href="#enter_AIS">AIS</a>

            </li>
            <li class='submenu'><a href="#enter_GIS">GIS</a>

            </li>
        </ul>
    </li>

CSS - 首先隐藏子菜单

#enter_scheme_global {
    display:none;
}

的jQuery

$(".enter-top-level").hover(function () {
    $(".enter-top-level ul").slideDown("slow");
    $(this).parent().css({"background-color" : "#700000"})
}, function(){
    $(".enter-top-level ul").slideUp("slow");
    $(this).parent().css({"background-color" : "#C8C8C8"});
});

答案 1 :(得分:0)

试试这个:

$("a").hover(
  function() {
     $(this).next('ul').slideToggle(500); // 'next' finds the next occurring element to the current 'a' tag
     $(this).next('ul').find('.submenu').css({"background-color" : "#700000"});
  }, function() {
    $(this).next('ul').slideToggle(500);
    $(this).next('ul').find('.submenu').css({"background-color" : "#C8C8C8"});
  }
);

工作示例:https://jsfiddle.net/9882acxn/4/