今天碰到一个需求是在输入框中,当输入框中输入文字时,显示清除按钮。
在网上找了一个案例,https://blog.csdn.net/qq_26780317/article/details/79002409,
是基于jquery实现的,我又基于原生js,写了一个。
html代码和案例中的一致,获取焦点的js代码如下:
var searchInput = document.getElementById("searchInput");
var clearInput =document.getElementById("searchTextCancel");
//输入框input获取焦点事件
searchInput.onfocus=lang.hitch(this,function(){
clearInput.style.display="block";
});
//输入框input失去焦点事件
searchInput.onblur=lang.hitch(this,function(){
if(searchInput.value == ""){
clearInput.style.display="none";
}
});
//输入框清除按钮点击事件
clearInput.onclick=lang.hitch(this,function(){
searchInput.value = "";
clearInput.style.display="none";
});