html移動應用 input 標籤 清除按鈕功能如何實現(不觸發鍵盤)
有個需求是:輸入框有文字的時候就顯示清除按鈕,沒有文字則隱藏清除按鈕,點選清除按鈕不能影響鍵盤彈出的狀態。
網上有css實現自動顯示和隱藏清除按鈕的方案,但是考慮到相容性,我們還是使用js來實現。
css
body{
background: #eee;
}
form{
margin: 30px 0;
position: relative;
}
#keyword{
height: 90px;
font-size: 60px;
line-height: 90px;
width: 300px;
}
#clear{
color: red;
width: 90px;
height: 90px;
line-height: 90px;
text-align: center;
position: absolute;
top: 0;
left: 210px;
visibility:hidden;
}
html
<form onsubmit="return false;" >
<input type="button" id="clear" value="clear">
<input type="search" id="keyword">
</form>
js
var keyword = document.getElementById('keyword'),
clear=document.getElementById('clear'),
autoShow=function () {
clear.style.display=keyword.value.length>0?'block':'none';
clear.style.visibility=keyword.value.length>0?'visible':'hidden';
};
keyword.oninput=autoShow;
clear.onmousedown=function (e) {
keyword.value = '';
autoShow();
keyword.focus();
e.preventDefault();
e.stopPropagation();
return false;
};