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
551 views
in Technique[技术] by (71.8m points)

drop down menu - Is there a CSS way to add an arrow if a ul has a ul child?

My navigation structure looks like this:

<div class="menu">
    <ul>
        <li><a href="#">Page 1</a></li>
        <li><a href="#">Page with Subpages</a>
            <ul class="children">
                <li><a href="#">Page with another subpage</a>
                    <ul class="children">
                        <li><a href="#">subsubpage</a></li>
                    </ul>
                </li>
            </ul>
        </li>
        <li><a href="#">Page 3</a></li>
        <li><a href="#">Page 4</a></li>
    </ul>
</div>

I want all <li>'s that have a subnavigation children to have a little down-arrow applied so users know this page has subpages.

Is it possible to detect in pure css if a <li> has children of ul.children? In my example above, the "Page with Subpages" should have the down arrow applied and the "Page with another subpage" as well.

Right now I'm using jquery to solve this problem:

$(function() {
    $('.menu a').each(function() {
        if ( $(this).parent('li').children('ul').size() > 0 ) {
            $(this).append('<span class="dwn">▼</span>');
        }           
    });
});

Is there an easy pure CSS way to do so?

Thank you.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is perfectly doable in CSS --

Your structure is this:

 <ul class="menu">
      <li>
           <a href="#">Has arrow</a>
           <ul><li><a href="#"></a></li></ul>
      </li>
      <li>
           <a href="#">Has no arrow</a>
      </li>
  </ul>

Your CSS will be like this --

   //this adds an arrow to every link
  .menu li > a:after { content: '>'; } 

  // this removes the arrow when the link is the only child
  .menu li > a:only-child:after { content: ''; }   

Taking it one step farther, if you want to have a drop down menu where there is a down arrow on the top level items and then right arrows for sub menus, your CSS would look like this

   // set up the right arrows first
   .menu li > a:after { content: '>'; }

   //set up the downward arrow for top level items
   .menu > li > a:after {content: 'v'; }

   //clear the content if a is only child
   .menu li > a:only-child:after {content: ''; }

Here is a jsfiddle of it in action - http://jsfiddle.net/w9xnv/2/


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

...