【问题标题】:Keep an icon in place after the user entered a text in an input用户在输入中输入文本后保留图标
【发布时间】:2017-12-27 20:29:10
【问题描述】:

我正在尝试在输入中转换搜索图标和输入占位符,因此当用户“关注”输入时,占位符和搜索图标使用转换被推到左侧,我没有问题到目前为止,除了...当我输入输入时,我希望图标在聚焦后保持在原位,如果输入内有文本。所以现在如果你输入一个文本然后点击离开输入当然图标会回到原来的位置,因为用户“模糊”了输入。

我希望图标保持在左侧,仅当输入中有文本时。

HTML:

<input type="text" id="search-input" placeholder="Search stuff...">
<svg height="32px" width="32px" version="1.1" viewBox="0 0 32 32" id="search-icon">
    <g id="Page-1" fill="none" stroke="none" strokeWidth="1">
        <g id="icon-111-search">
            <path id="search" d="M19.4271164,21.4271164 C18.0372495,22.4174803 16.3366522,23 14.5,23 C9.80557939,23 6,19.1944206 6,14.5 C6,9.80557939 9.80557939,6 14.5,6 C19.1944206,6 23,9.80557939 23,14.5 C23,16.3366522 22.4174803,18.0372495 21.4271164,19.4271164 L27.0119176,25.0119176 C27.5621186,25.5621186 27.5575313,26.4424687 27.0117185,26.9882815 L26.9882815,27.0117185 C26.4438648,27.5561352 25.5576204,27.5576204 25.0119176,27.0119176 L19.4271164,21.4271164 L19.4271164,21.4271164 Z M14.5,21 C18.0898511,21 21,18.0898511 21,14.5 C21,10.9101489 18.0898511,8 14.5,8 C10.9101489,8 8,10.9101489 8,14.5 C8,18.0898511 10.9101489,21 14.5,21 L14.5,21 Z" />
        </g>
    </g>
</svg>

CSS:

#search-input {
  padding: 5px;
  width: 220px;
  border-radius: 3px;
  border: 1px solid #ECECEC;
  background: #FCFCFC;
  text-indent: 23px;
  outline: none;
}

#search-input::-webkit-input-placeholder {
  position: relative;
  padding-left: 45px;
  transition: padding 0.2s;
}

#search-input:focus::-webkit-input-placeholder {
  padding-left: 0px;
}

#search-icon {
  width: 26px;
  height: 26px;
  position: absolute;
  left: 60px;
  top: 8px;
  transition: left 0.2s;
}

#search-input:focus + #search-icon {
  left: 10px;
}

#search-icon path {
  fill: #666;
}

我的笔在右边here

我不介意将 JavaScript 包含在解决方案中,因为它是一个 SPA,而且它是一个 React 项目,因此 React 相关的解决方案是首选但不是必需的。

【问题讨论】:

    标签: javascript html css reactjs


    【解决方案1】:

    我能想到的一种方法是:

    • 将 :focus 修饰符 css 转换为类。

    • 将两个事件添加到搜索输入 onFocus 和 onblur

    • 在 onfocus 回调中添加类并在 onblur 中移除 仅当输入框为空时回调。

    【讨论】:

    • 这听起来是个好主意,我正在等待代码解决方案,如果没有其他人我会确认它。
    • 我已经实施了该解决方案,并确认了您的解决方案。
    【解决方案2】:

    你可以使用:placeholder-shownhttps://caniuse.com/#search=placeholder-shown

    input:not(:placeholder-shown) {
      background-color: yellow;
    }
    &lt;input type="text" placeholder="Search"&gt;

    【讨论】:

    • 我知道那个解决方案,但它不支持很多浏览器。
    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 2018-04-10
    • 2011-01-18
    • 1970-01-01
    • 2012-05-05
    • 2016-05-20
    • 2016-12-18
    • 2015-08-10
    相关资源
    最近更新 更多