如何在移动web模仿客户端给input输入框添加自定义清除按钮

项目有个需求就是在input输入框添加清除按钮,网上查找资料加上自己琢磨终于弄出来了。

灵感来自于 http://www.zhangxinxu.com/wordpress/?p=4077

由于项目已经上线给为了减少改动就改为通过js全局控制的方式,就不改html了。

css部分:

 1 /*输入框清除按钮*/
 2 .iss-close{
 3     position: absolute;
 4     top: 0;
 5     color: #ccc!important;
 6     display: none;
 7     cursor: pointer;
 8     z-index: 9999;
 9 }
10 input:valid + .iss-close {
11     display: inline-block;
12 }
13 .iss-close-hide{
14     display: none!important;
15 }

 

js部分:

 1 //统一添加清除按钮和清除按钮事件处理
 2 $("input").attr("required","required");
 3 $("input[type=file],input[type=reset],input[type=submit],input[type=password],input[type=image],input[type=radio],input[type=checkbox],input[type=hidden],input[type=button],input[type=date],input[type=month],input[types=date],input[types=month],input.iss-search,input[readonly],input[disabled]").removeAttr("required");
 4 setTimeout(function(){
 5     $("input[required]").each(function(){
 6         $(this).after('<a class="iss-close">'+
 7             '<i class="issfont iss-icon-font-round-close-fill"></i>'+
 8             '</a>').next().css({"right":$(this).parent().css("paddingRight"),"marginRight":"-10px"})
 9     });
10 },1000);
11 
12 //模拟ios客户端获取焦点时显示清除按钮,离开焦点隐藏清除按钮
13 $("input[required]").focus(function(){
14     $(this).next(".iss-close").removeClass("iss-close-hide")
15 }).blur(function(){
16     $(this).next(".iss-close").addClass("iss-close-hide")
17 });
18 
19 //点击清除按钮
20 $(".iss-close").live("tap",function(e){
21     e.preventDefault();
22     e.stopPropagation();
23     $(this).prev("input").val("");
24 });

 

实现效果如下:  

 

posted @ 2017-06-30 11:33  大圣巴巴  阅读(3216)  评论(0编辑  收藏  举报