【问题标题】:Hide element when precedent input is empty and not focused当先例输入为空且未聚焦时隐藏元素
【发布时间】:2020-05-20 17:27:17
【问题描述】:

是否可以使用 CSS/PostCSS (magic) 仅在目标输入聚焦且不为空时才显示后续元素?

当输入焦点集中时,我已经完成了一半的显示,但还不知道是否将焦点和空结合在一起?

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>

【问题讨论】:

标签: css postcss


【解决方案1】:

其实@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>

【讨论】:

  • 感谢您的建议,这很有魅力。我查看了@Paulie_D 分享的文章,提示使用:placeholder-shown 也可以与:not focus 结合使用:-)
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 2023-02-23
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 2022-12-31
  • 2016-10-06
  • 1970-01-01
相关资源
最近更新 更多