有个需求是:输入框有文本的时候就显示清除按钮,没有文本则隐藏清除按钮,点击清除按钮不能影响键盘弹出的状态。
网上有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 =\"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. =function (e) {
keyword.value = \'\';
autoShow();
keyword.focus();
e.preventDefault();
e.stopPropagation();
return false;
};
继续阅读与本文标签相同的文章
神经网络开始放飞自我!都是因为架构搜索新算法
-
给网站添加微信扫描二维码登录功能
2026-05-19栏目: 教程
-
Sharding-Jdbc之读写分离导读
2026-05-19栏目: 教程
-
Sharding-Jdbc分库分表的导读
2026-05-19栏目: 教程
-
日志服务数据加工培训直播资料汇总: 扫平日志分析路上障碍, 实时海量日志加工实践
2026-05-19栏目: 教程
-
OCP-052考试题库汇总(46)-CUUG内部解答版
2026-05-19栏目: 教程
