现在已经实现了小程序中的input输入框的功能了:
但是现在想要在输入框input内部的右边加上一个clear close的button,用于点击清除输入:

类似于已有web版中的效果:

小程序 输入框 清除 按钮
被人是用image实现的
自己去找找,记得小程序中有icon的
是有要的:

先去显示这个clear的icon
然后去参考:
的代码:

先用代码:
1 | <icon type = "clear" size= "20" /> |
显示出来清除按钮了:

然后再去想办法看看能否让其在input的内部靠右显示出来
参考:
-》

以及自己之前的web版:

去折腾试试
此处基本上实现了要的效果
不过遇到了:
虽然清空了内部的值,但是input显示的值,还存在:


所以要去解决:
小程序 清空 input
把value绑定一个值即可
去试试:
1 2 | < input > value=""> |
改为:
1 2 | < input > value="{{curInputValue}}"> |
果然可以:

【总结】
此处用:
pages/index/index.wxml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | < input id = "queryInput" bindinput = 'inputCallback' bindconfirm = "inputConfirmCallback" type = "text" placeholder = "请输入要查询的英文绘本名称" value = "{{curInputValue}}" > <view class = 'clear_input {{isShowClear ? "show_clear" : "hide_clear"}}' > <icon class = "clear_button" type = "clear" size = "18" bindtap = 'clearInput' / > < / view> < / input > <button id = "queryButton" bindtap = "submitQuery" >查询< / button> < / view> |
pages/index/index.wxss
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | .input_and_query{ height: 28px; vertical-align: center; margin-bottom: 44px; display: flex; width: 100%; } #queryInput{ font-size: 13px; border-radius: 16px; border: 1px solid #ced4da; margin-left: 39px; /* flex:0 0 80%; */ /* flex-grow: 4; */ flex: 1 1 70%; /* text-indent: 8px; */ padding-left: 8px; padding-right: 28px; position: relative; } .clear_input{ align-items: center; justify-content: center; right: 6px; position: absolute; bottom: 4px; z-index: 10; } .show_clear{ display: flex; } .hide_clear{ display: none; } .clear_button{ } |
pages/index/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | Page({ data: { curInputValue: "", isShowClear: false, }, / / 事件处理函数 inputCallback: function (e) { console.log( "inputCallback: e=%o" , e) this.setData({ curInputValue: e.detail.value }) console.log( "curInputValue=%s" , this.data.curInputValue) var isShowClear = false if (this.data.curInputValue){ isShowClear = true } else { isShowClear = false } this.setData({ isShowClear: isShowClear }) }, clearInput: function (e) { console.log( "clearInput: e=%o" , e) this.setData({ curInputValue: "", isShowClear: false }) }, }) |
即可实现效果:

输入了点内容:

点击清除按钮后,即可清除内部的值,同时内部的值curInputValue同步到input的value上,input的显示的值也清空了:

且还支持,输入足够长的内容后,右边padding的位置,不会被清除按钮遮盖和重叠:
