我可以在输入占位符中放置 <span> 吗?

Can I put a <span> inside of an input placeholder?

我正在做一个有这样输入的项目:

    <div className="search__bar__description form__control">
        <input
            placeholder="Filter by title, companies, expertise..."
            aria-label="Enter company, title, or expertise here"
            onChange={e => setSearchInput(e.target.value)}
            value={searchInput}
        />
    </div>

当网站在桌面上时,我想要整个长占位符,但在移动设备上时,我希望占位符只是说 Filter by title...

我正在想办法做到这一点 CSS。我可以在占位符中放置一个 span 然后隐藏它吗?那是有效的 HTML 吗?如果它不是 W3C 有效的 HTML 你能告诉我怎么做吗?

提前致谢!

不能将跨度放在占位符内。

您想要实现的目标的常见解决方案是将占位符文本作为单独的元素,置于文本字段的下方。然后你可以做任何你想要的标记和样式。这当然要付出更多的努力,但这就是定制工程的方式。

您可以在此处查看高级示例:https://css-tricks.com/float-labels-css/

如果忽略动画,他的代码示例中的 take-away 是使用 <label> 元素而不是占位符属性,并且位于输入字段后面,因此看起来相同,但随后可以使用与任何其他标准元素相同的 CSS(在他的情况下,添加一些花哨的过渡)和 sub-elements 进行操作。

首先,您不需要 JavaScript 来执行此操作。虽然您不能将 span 放在 input 中,但您可以使用 :placeholder-shown pseudo-class 执行一些技巧来实现您所追求的目标。在 post 时,浏览器对此 pseudo-class 的支持是 really good

来自MDN

The :placeholder-shown CSS pseudo-class represents any <input> or <textarea> element that is currently displaying placeholder text.

此示例使 smaller-sized 屏幕上的输入占位符颜色透明,视觉上将其隐藏。包含短标签的 span 然后显示在此断点处。请注意它的样式和位置,以便它看起来尽可能接近原始占位符文本。最后,使用上面提到的 pseudo-class,当原始占位符 not 显示时(当输入不为空时),我们隐藏短标签。

.form__control {
  position: relative;
}

.short-label {
  display: none;
  pointer-events: none;  
}

@media screen and (max-width: 700px) {
   ::placeholder {
    color: transparent;
  }

  .short-label {
    position: absolute;
    left: 4px;
    top: calc(50% + 1px);
    transform: translateY(-50%);
    font-size: 11px;
    color: rgb(43%, 43%, 43%);
    font-family: sans-serif;
    letter-spacing: 0.4px;
    display: block;
    font-weight: lighter;
  }

  input:not(:placeholder-shown)+.short-label {
    display: none;
  }
}
<div class="search__bar__description form__control">
  <input placeholder="Filter by title, companies, expertise..." aria-label="Enter company, title, or expertise here" />
  <span class="short-label">Filter by title...</span>
</div>

jsFiddle