如何使用常规文本输入上的清除“x”按钮获取搜索输入的行为?

Ela*_*ter 2 html css

我正在尝试<input type="search">定期获取行为<input type="text">

我尝试使用appearance: searchfield;没有应用这种特殊行为的 。

我希望它看起来如何: 在此处输入图片说明

CodePen 示例(在 Chrome 浏览器上测试,但不起作用)

寻找纯 CSS/HTML 解决方案

vsy*_*ync 5

演示:https : //codepen.io/vsync/pen/MWjdbgL

这里介绍三种解决问题的方法:

1?? 当input元素没有焦点时,它type被设置为search,然后显示x(清除按钮),当元素有焦点时- 它的类型被设置为text

<input type="search" 
       onmouseup="this._timer=setTimeout(el=>{el.type='text'},0,this)" 
       onblur="clearTimeout(this._timer);this.type='search'" 
/>
Run Code Online (Sandbox Code Playgroud)

2?? 用<form>元素包装输入,以便可以使用本机将其清除
<button type='clear'>

input{ padding:.5em; font:1em Arial;}
input[type='text']:placeholder-shown + button{ opacity:0; pointer-events:none;}

form{ display:inline-block; position: relative; }
form:hover input[type='text']:not(:placeholder-shown) + button{ opacity: 1 }
form button{
    --size: 18px;
    position: absolute;
    border: none;
    display: block;
    width: var(--size);
    height: var(--size);
    line-height: var(--size);
    font-size: calc(var(--size) - 3px);
    border-radius: 50%;
    top: 0;
    bottom: 0;
    right: calc(var(--size)/2);
    margin: auto;
    background-color: salmon;
    color: white;
    padding: 0;
    outline: none;
    cursor: pointer;
    opacity: 0;
    transition: .1s;
}
Run Code Online (Sandbox Code Playgroud)
<form>
  <input type='text'  placeholder=' ' />
  <button type='reset'>&times;</button>
</form>
Run Code Online (Sandbox Code Playgroud)

3?? 使用<form>包装器和 javascript

input{ padding:.5em; font:1em Arial; }
input[type='text']:placeholder-shown + button{ opacity:0; pointer-events:none;}

.inputWrap{ display:inline-block; position: relative; }
.inputWrap:hover input[type='text']:not(:placeholder-shown) + button{ opacity: 1 }
.inputWrap button{
    --size: 18px;
    position: absolute;
    border: none;
    display: block;
    width: var(--size);
    height: var(--size);
    line-height: var(--size);
    font-size: calc(var(--size) - 3px);
    border-radius: 50%;
    top: 0;
    bottom: 0;
    right: calc(var(--size)/2);
    margin: auto;
    background-color: salmon;
    color: white;
    padding: 0;
    outline: none;
    cursor: pointer;
    opacity: 0;
    transition: .1s;
}
Run Code Online (Sandbox Code Playgroud)
<div class='inputWrap'>
  <input type='text'  placeholder=' ' />
  <button type='reset' onclick='this.previousElementSibling.value=""'>&times;</button>
</div>
Run Code Online (Sandbox Code Playgroud)