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;
     };


posted @   JoVee  阅读(1176)  评论(0编辑  收藏  举报
编辑推荐:
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
阅读排行:
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· RFID实践——.NET IoT程序读取高频RFID卡/标签
点击右上角即可分享
微信分享提示