Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

menu - jQuery hover event with nested elements

I've currently got your basic, run-of-the-mill menu tree as follows:

<ul id="nav">
  <li>
    <a href="#">home</a>
    <div class="controls">Some controls go here</div>
    <ul>
      <li>
        <a href="#">item 1</a>
        <div class="controls">Some controls go here</div>
      </li>
      <li>
        <a href="#">item 2</a>
        <div class="controls">Some controls go here</div>
      </li>
    </ul>
  </li>
</ul>

The divs with the "controls" class are hidden to start with. What I want to happen is that when you hover over an li, the controls for that respective li show (when you move your mouse away, they hide again). The problem occurs when you hover over one of the nested li's, it display's it's parents controls as well. Here is the jQuery I'm using:

    $("#nav li").hover(
        function() {
            $(".controls:first", this).css("display", "block");
        },
        function() {
            $(".controls:first", this).css("display", "none");
        }
    );

Thanks for your help. Remy

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try stopping event propagation in the hover function to prevent the event from bubbling up to the parent. You might also want to look at the hoverIntent plugin to solve issues of "flashing" hover effects if your "hovered" elements are close together.

$("#nav li").hover(
    function(e) {
            e.stopPropagation();
            $(".controls:first", this).css("display", "block");
        },
        function() {
            $(".controls:first", this).css("display", "none");
        }
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...