【问题标题】:How to get the clear 'X' button inside the input field?如何在输入字段中获取清除“X”按钮?
【发布时间】:2022-02-16 06:31:09
【问题描述】:

我创建了一个搜索字段,用户可以在其中输入一些文本。搜索字段旁边是一个“X”按钮,用于清除搜索输入。我注意到的问题是,在我的手机上,“X”按钮就在输入搜索框之外:Here is the example。如何让“X”出现在搜索框中?

HTML:

<input id="myInput" type="text" placeholder="Search Text...">
<button class="clear">X</button>

CSS:

#myInput{
    width: 40%;
    height: 33px;
    border: 1px solid #000;
    font-family: 'arial';
    font-size: 19px;
}
.clear {
    position: relative;
    z-index: 1;
    margin-left: -29px;
    background: transparent;
    border: 0px none;
    font-size: 19px;
    font-weight: bold;
    vertical-align: middle;
}

【问题讨论】:

  • type="search" 已经在大多数浏览器中实现了

标签: javascript html css sass


【解决方案1】:

解决这个问题的最简单方法是使用position: relative + width: min-content 将输入和按钮包装在一个元素中。那么你只需要在按钮上应用position: absolute + right: value

.wrapper {
  position: relative;
  width: min-content;
}

.clear {
  position: absolute;
  right: 0px;
}
<div class="wrapper">
  <input id="myInput" type="text" placeholder="Search Text...">
  <button class="clear">X</button>
</div>

【讨论】:

    【解决方案2】:
    <input type="search" />
    

    至少在基于 Chromium 的浏览器中工作。不过,它确实有一些未记录的副作用,例如 ESC 会清除输入。


    如果您打算使用自己的自定义清除按钮,可以通过将这两个元素放入共享的父元素来适应这个想法。让input 占据父元素的整个大小,然后在清除按钮上使用position: absolute;

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多