一、问题描述
多个输入框,每次聚焦时全选中输入框内容,使用了selectionStart和selectionEnd属性,但只有一次选中内容
<view wx:for="{{testList}}">
<view class="flex-row-center">
<text>{{item.label}}: </text>
<input class="inputs" type="text"
value="{{ item.value }}"
selection-start="{{item.selectionStart}}"
selection-end="{{item.selectionEnd}}"
data-index="{{ index }}"
bindinput="amountWater"
/>
</view>
</view>
二、分析
仔细看了文档,selectionStart和selectionEnd属性是需要在自动聚焦时才有效的。
需求是要点击输入框时自动聚焦触发selectionStart和selectionEnd属性,那么我更新如下
<view wx:for="{{testList}}">
<view class="flex-row-center">
<text>{{item.label}}: </text>
<view wx:if="{{!item.focus}}"
class="inputs"
data-index="{{ index }}"
bindtap="bindInputPitch">{{ item.value }}</view>
<input wx:else class="inputs" type="text"
value="{{ item.value }}"
selection-start="{{item.selectionStart}}"
selection-end="{{item.selectionEnd}}"
focus="{{ item.focus }}"
data-index="{{ index }}"
bindinput="amountWater"
bindblur="bindInputBlur"
/>
</view>
</view>
点击代替input框的元素,激活自动聚焦
bindInputPitch (evt) {
const { testList } = this.data
const { index } = evt.currentTarget.dataset
const quantity = testList[index].value || 0
this.setData({
[`testList[${index}].focus`]: true,
[`testList[${index}].selectionStart`]: 0,
[`testList[${index}].selectionEnd`]: quantity.toString().length
})
},
输入框失焦时
bindInputBlur (evt) {
const { index } = evt.currentTarget.dataset
let { testList } = this.data
this.setData({
[`testList[${index}].value`]: testList[`${index}`].value <= 0 ? 0 : testList[`${index}`].value,
[`testList[${index}].focus`]: false,
[`testList[${index}].selectionStart`]: -1,
[`testList[${index}].selectionEnd`]: -1
})
},
使用障眼法,借用普通元素的点击事件来激活自动聚焦。
三、总结
认真看文档,多思考,不懂就问,遇到问题并解决了问题要及时记录下,避免下次遇相同问题不知所措。
以上是我的解决方法,兄弟们如果还有其他方法可分享一下