当前位置: 动力学知识库 > 问答 > 编程问答 >

Traversing HTML tags Tree with CSS selectors

问题描述:

<div>

<div class="header">

<div id="navbar" >

<ul id="nav">

<li><a id="trigger"><span><p></p></span></a></li>

<li><a id="target"><span><p></p></span></a></li>

</ul>

</div>

</div>

</div>

hey guys, I've got a question, if it wouldn't causing any inconvenience to you guys, in relation with traversing in HTML tree.

I already know how to choose the <a id="trigger"></a> with this syntax:

div>div.header>div#navbar>ul#nav>li>a#trigger:hover {CSS} will trigger changes.

But here's the problem, I wanted to target the <a id="target""></a> tag underneath it but I haven't found the right syntax for accessing the <a id="affected"></a> there.

I want when I hover the id="trigger", the id="target" will be affected.

I've already tried using + selectors to target that id, alas, the trials ended in vain.

Is it possible to affect that id?

网友答案:

You probably want the adjacent sibling selector:

#trigger:hover + #target {}

Or maybe the sibling combinator, which doesn't require that the second element be directly adjacent:

#trigger:hover ~ #target {}

http://css-tricks.com/child-and-sibling-selectors

UPDATE: As is stated in the comments below, the selectors must actually be siblings. In the original structure, they're not.

<div>
  <div class="header">
    <div id="navbar" >
      <ul id="nav">
        <li class="one"><a id="trigger">Trigger</a></li>
        <li class="two"><a id="target">Target</a></li>
      </ul>
    </div>
  </div>
</div>

.one:hover + .two {color: red}

http://jsfiddle.net/5Gmz9/1/

Here's another approach which doesn't require classes or IDs on the li elements:

#nav li:first-child:hover + li {color: red}

http://jsfiddle.net/5Gmz9/2/

Each approach has its pitfalls.


By the way,

div>div.header>div#navbar>ul#nav>li>a#trigger:hover {}

could probably be as well written as

#navbar #trigger:hover {}

saving you and the browser both some work.

分享给朋友:
您可能感兴趣的文章:
随机阅读: