是否可以使用 CSS/PostCSS(魔术)仅在目标输入聚焦且不为空时显示后续元素?
当输入聚焦时,我已经完成了一半的显示,但还不知道是否可以将聚焦和空结合在一起?
input:not(:focus) + button {
opacity: 0;
pointer-events: none;
touch-action: none;
}
input:not(:focus):not(:empty) + .notEmptyCase {
opacity: 0;
pointer-events: none;
touch-action: none;
}
<p>Button gets visible when input is focused</p>
<input placeholder="Search">
<button>CLEAR</button>
<p>Button gets visible when input is focused and isn't empty</p>
<input placeholder="Search">
<button class='notEmptyCase'>CLEAR</button>
最佳答案
其实@Paulie_D是对的,你不能用:empty
伪类来实现这一点,但这对于 CSS 来说并非不可能,但是,做到这一点非常棘手。 你应该使用:not
(:valid)
或 :invalid
伪类 来实现这样的事情,所以要使用它,您还需要使您的 input
成为必需的(这是肯定的)。然后,当您使用此伪类时,在您的特定情况下无需检查输入是否聚焦。
input:not(:focus) + button {
opacity: 0;
pointer-events: none;
touch-action: none;
}
input:invalid + .notEmptyCase {
opacity: 0;
pointer-events: none;
touch-action: none;
}
<p>Button gets visible when input is focused and isn't empty</p>
<input placeholder="Search">
<button class='notEmptyCase'>CLEAR</button>
<p>Button gets visible when input is focused and isn't empty</p>
<input type="text" placeholder="Search" required>
<button class='notEmptyCase'>CLEAR</button>
关于css - 当先行输入为空且未获得焦点时隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61908412/