gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:24:18 27 4
gpt4 key购买 nike

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

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

我想要它的外观: enter image description here

CodePen Example (在Chrome浏览器上测试,无效)

寻找纯 CSS/HTML 解决方案

最佳答案

演示: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'"
/>

2️⃣ 用 <form> 包裹输入元素,以便可以使用 native
<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;
}
<form>
<input type='text' placeholder=' ' />
<button type='reset'>&times;</button>
</form>

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;
}
<div class='inputWrap'>
<input type='text' placeholder=' ' />
<button type='reset' onclick='this.previousElementSibling.value=""'>&times;</button>
</div>

关于html - 如何使用常规文本输入上的清除 "x"按钮获取搜索输入的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65934208/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com