css 如何选择一个psoudo元素(后)更改样式在无效和有效的输入

y53ybaqx  于 2023-07-01  发布在  其他
关注(0)|答案(2)|浏览(142)

我在输入后加上 *,我想在input:validinvalid中选择这个来改变颜色,但是这个CSS不起作用为什么?

form::after {
    content: "*";
}

#fname:invalid~::after {
    background: red;
    border-color: yellow;
}

#fname:valid~::after {
    background: rgb(3, 183, 168);
    border-color: rgb(9, 9, 0);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     <form action="/action_page.php" id="frm">
        <label for="fname">First name:</label><br>
        <input required type="text" id="fname" value=""><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>
soat7uwm

soat7uwm1#

您可以使用:has()(在layout.css.has-selector.enabled标志后面的Firefox中支持):

#frm:after {
  content: "*";
}

#frm:has(#femail:invalid):after {
  background: red;
}

#frm:has(#femail:valid):after {
  background: rgb(3, 183, 168);
}
<form action="?" id="frm">
  <label for="fname">Email:</label><br>
  <input required type="email" id="femail"><br><br>
  <input type="submit" value="Submit">
</form>

或者简单地将<form>中的:after替换为<span>*</span>

#femail:invalid ~ span {
  background: red;
}

#femail:valid ~ span {
  background: rgb(3, 183, 168);
}
<form action="?" id="frm">
  <label for="fname">Email:</label><br>
  <input required type="email" id="femail"><br><br>
  <input type="submit" value="Submit">
  <span>*</span>
</form>
hvvq6cgz

hvvq6cgz2#

::after替换为span

<form action="/action_page.php" id="frm">
    <label for="fname">First name:</label><br>
    <input required type="text" id="fname" value=""><br><br>
    <span>span</span>
    <input type="submit" value="Submit">
</form>
input:valid + span::after {
  content: "";
  background: red;
}

相关问题