首页 > 解决方案 > 单击时css更改占位符(无js)

问题描述

我正在尝试实现一个文本栏。它必须是这样的:

我的目标

关于使用的语言,你只需要知道它是从右到左写的。输入元素内的文本是一个占位符。当我单击文本框(不是放大镜图标)时,它变成这样:

在此处输入图像描述

请注意,放大镜图标已经消失,现在整个区域都可以输入了。我想使用 CSS 而不是 javascript 来实现它。我试图将放大镜的 svg 元素添加到输入的占位符属性中,但失败了。现在,我已经实现了第二个形状(点击后),但它没有响应并且没有放大镜 svg 作为占位符。

作为对我的代码的简要说明,我有一个用于整个容器的大 div,它是一个列 flex,一个顶部 div,顶部标题在那里,我给了它的下边界。和输入栏。这是我已经实现的:

在此处输入图像描述

顺便说一句,我可以访问 svg 元素:

<svg data-v-027aed6c="" xmlns="http://www.w3.org/2000/svg" width="1.2em" height="1.2em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="position-absolute search-icon text-steel feather feather-search"><circle data-v-027aed6c="" cx="11" cy="11" r="8"></circle><line data-v-027aed6c="" x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>

我可以将它添加到我的输入文本栏的右侧,但我不知道如何在没有 js 的情况下使其响应。

标签: csssvg

解决方案


您正在寻找的选择器是:placeholder-shown. 它适用于 v79 之前除 Edge 之外的所有浏览器,对于 IE,您可以使用前缀形式:-ms-placeholder-shown。(我会把完整的样式留给你。)

这里唯一需要注意的是,在源顺序中,<svg>需要在<input>元素之后。在 RTL 编写模式下,这可能意味着您需要重新排序两者,例如使用 flexorder属性。

span {
  display: flex;
  align-content: stretch;
  height: 2em;  
  direction: rtl;
}
input[type="text"] {
  order:2;
  height: 2em;
  border: 1px solid #666;
  margin: 0;
  box-sizing: border-box;
}
svg {
  order: 1;
  width: 2em;
  height: 2em;
  border: 1px solid #666;
  border-left: none;
  padding: 4px;
  box-sizing: border-box;
}
input[type="text"] + svg * {
    display: none;
}
input[type="text"]:placeholder-shown + svg * {
    display: inline;
}
<span>
  <input type="text" placeholder="text">
  <svg data-v-027aed6c="" xmlns="http://www.w3.org/2000/svg" width="1.2em" height="1.2em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="position-absolute search-icon text-steel feather feather-search">
    <circle data-v-027aed6c="" cx="11" cy="11" r="8"></circle>
    <line data-v-027aed6c="" x1="21" y1="21" x2="16.65" y2="16.65"></line>
  </svg>
</span>


推荐阅读