今天碰到一個需求是在輸入框中,當輸入框中輸入文字時,顯示清除按鈕。
在網上找了一個案例,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";
});