gpt4 book ai didi

javascript - 带有自动隐藏和显示的清除按钮的文本输入

转载 作者:太空宇宙 更新时间:2023-11-04 15:38:25 27 4
gpt4 key购买 nike

我正在开发一个使用搜索框的网站,并且在该搜索输入字段内我想设置一个重置按钮“X”

因此,当搜索框输入字段为空时,它不会显示“X”。但是当用户在字段中输入任何内容时,“X”将自动显示。

同样,当用户单击“X”时,它将清除所有键入的数据并仍然聚焦在输入字段内?

到目前为止我已经做到了

只有 JavaScript 代码,我不使用 jQuery!

var searchSminput = document.getElementById("offcansearch").value.length;

if (searchSminput == 0) {
document.getElementById("resetb").style.display = "none";
} else {
document.getElementById("resetb").style.display = "block";
}
	#resetb {

background-image: url(http://cdn.onlinewebfonts.com/svg/img_286433.svg);
background-repeat: no-repeat;
background-size: 22px 42px;
cursor: pointer;
display: block;
transition: all 300ms ease;
width: 22px;
height: 42px;
border: none;
background-color: transparent;
outline: none;
right: 10px;
top: 5px;
position: absolute;
margin: 0;
padding: 0;
}
#offcansearch {
width: 100%;
height: 30px;
}
<form>
<input id="offcansearch" type="text" name="search" placeholder="Search">
<button id="resetb" type="reset"></button>
</form>

最佳答案

向输入添加更改事件:

document.getElementById('offcansearch').addEventListener('change', function() { ... }

同时添加重置按钮(单击时隐藏按钮):

resetb.addEventListener('click', function() {
resetb.style.display = "none";
});

var resetb =  document.getElementById("resetb");
var offcansearch = document.getElementById('offcansearch');

offcansearch.addEventListener('keyup', function() {
var searchSminput = offcansearch.value.length;
if (searchSminput == 0) {
resetb.style.display = "none";
} else {
resetb.style.display = "block";
}
});

resetb.addEventListener('click', function() {
resetb.style.display = "none";
offcansearch.focus();
});
#resetb {
background-image: url(http://cdn.onlinewebfonts.com/svg/img_286433.svg);
background-repeat: no-repeat;
background-size: 22px 42px;
cursor: pointer;
display: none;
transition: all 300ms ease;
width: 22px;
height: 42px;
border: none;
background-color: transparent;
outline: none;
right: 10px;
top: 5px;
position: absolute;
margin: 0;
padding: 0;
}

#offcansearch {
width: 100%;
height: 30px;
}
<form>
<input id="offcansearch" type="text" name="search" placeholder="Search">
<button id="resetb" type="reset"></button>
</form>

关于javascript - 带有自动隐藏和显示的清除按钮的文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44099515/

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