【问题标题】:Having trouble to select an element while other is in :target [closed]在其他元素位于时无法选择元素:target [关闭]
【发布时间】:2020-09-30 17:18:00
【问题描述】:

我刚刚开始学习如何使用html5和css3,我遇到了这个问题:

有没有办法在其他元素打开时选择其他元素 :tget with css?

让我用一个例子来解释:

Html:
<body>
<header>
<nav id="menu">
    <ul id="buttons">
       <li><a href="#">button</a></li>
       <li><a href="#">button</a></li>
    </ul>
</nav>
</header>

<section id="one">
   <h2>title</h2>
   <p>text</p>
<section>
</body>

我们的想法是将#menu 放在目标上并制作#one,例如,更改它的颜色。 我读过“兄弟选择器”(+ 和 ~ 我认为)如果两个元素都是身体的儿子,这是一个可能的解决方案吗?

对不起,我的英语不是我的母语。提前致谢!

【问题讨论】:

  • 应用类到 div 对你有帮助吗?

标签: html css target


【解决方案1】:

首先验证您的 HTML 代码

  1. 没有&lt;/ul&gt;关闭标签。

  2. &lt;/a&gt;标签不需要在&lt;li&gt;标签中。

<body>
    <header>
    <nav id="menu">
        <ul id="buttons">
           <li>text</li>
           <li>text</li>
        </ul>
    </nav>
    </header>
    
    <section id="one">
       <h2>title</h2>
       <p>text</p>
    <section>
</body>

如何使用:target

:target CSS 伪类表示一个唯一元素(目标元素),其 id 与 URL 的片段匹配。

/* Selects an element with an ID matching the current URL's fragment */
:target {
  border: 2px solid black;
}

例如,以下 URL 有一个片段(用 # 号表示)指向一个名为 section2 的元素:

http://www.example.com/index.html#section2

当当前 URL 等于上述元素时,:target 选择器将选择以下元素:

<section id="section2">Example</section>

工作演示

:target {
  color: #00cc00;
}
<h3>Table of Contents</h3>
<ol>
 <li><a href="#p1">Jump to the first paragraph!</a></li>
 <li><a href="#p2">Jump to the second paragraph!</a></li>
 <li><a href="#nowhere">This link goes nowhere,
   because the target doesn't exist.</a></li>
</ol>

<h3>My Fun Article</h3>
<p id="p1">You can target <i>this paragraph</i> using a
  URL fragment. Click on the link above to try out!</p>
<p id="p2">This is <i>another paragraph</i>, also accessible
  from the links above. Isn't that delightful?</p>

【讨论】:

  • 你说得对,谢谢。
  • 我更新了答案 :) 你想要这样吗?
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2018-06-23
  • 2013-08-23
  • 1970-01-01
相关资源
最近更新 更多