【问题标题】:How to use active and before with CSS?如何在 CSS 中使用 active 和 before?
【发布时间】:2016-05-18 22:13:43
【问题描述】:

我会使用伪类::before:active 创建一个CSS 效果。 我创建了一个效果,如果您单击之前 p 的元素,则 p 之前的内容会发生变化。 我认为这不起作用,因为在 p 之前无法选择。
这是我的代码,但不起作用:

.container {
  background-color: #222;
  border-radius: 5px;
  width: 200px;
  display: block;
  margin: 0 auto;
}

.container > p {
  color: #fff;
  padding: 10px;
  text-align: center;
}

.container > p::before {
  content: 'ON';
}

p:active + p:before {
  content: 'OFF';
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="container"><p></p></div>
</body>
</html>

【问题讨论】:

  • @DavidThomas — 不正确。您可以单击任何元素。互动与否。 (以这种方式设计网站是不好的做法,但不会对鼠标用户造成障碍)。
  • 还有...paragraphs are not buttons。如果你想要一个按钮...使用button
  • 注意。 :active 是一个伪类,但 ::before 创建了一个伪元素。不是一回事。

标签: html css pseudo-class


【解决方案1】:

p:active + p:before 表示出现在紧接在按下鼠标按钮时鼠标指向的(其他)段落之后的段落之前的伪元素.

由于您只有一个段落,因此无法匹配任何内容。

也许你的意思是p:active:before

.container {
  background-color: #222;
  border-radius: 5px;
  width: 200px;
  display: block;
  margin: 0 auto;
}

.container > p {
  color: #fff;
  padding: 10px;
  text-align: center;
}

.container > p::before {
  content: 'ON';
}

p:active:before {
  content: 'OFF';
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="container"><p></p></div>
</body>
</html>

【讨论】:

    【解决方案2】:

    将此规则 p:active + p:before 更改为 p:active:before

    .container {
      background-color: #222;
      border-radius: 5px;
      width: 200px;
      display: block;
      margin: 0 auto;
    }
    
    .container > p {
      color: #fff;
      padding: 10px;
      text-align: center;
    }
    
    .container > p::before {
      content: 'ON';
    }
    
    p:active:before {
      content: 'OFF';
    }
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body>
    <div class="container"><p></p></div>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2023-02-21
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 2014-10-08
      相关资源
      最近更新 更多