最近公司做移动端,用手点击时光标定位到最后一位。
具体代码
这是使用v-for循环的列表,当时van-field并没有id,需要手动添加 id
(后端请求回来数据带有id).
<van-field
:id="item.id"
:key="item.columnId"
v-for="item in detailColumns"
v-model="editForm"
@focus="handleFocus(item)"
/>
//将光标定位到最后一位
handleFocus(item) {
let tObj = document.getElementById(item.id);
this.$nextTick(function () {
if (item.value != undefined) {
let sPos = item.value.length;
if (tObj.setSelectionRange) {
tObj.setSelectionRange(sPos, sPos);
tObj.focus();
}
} else if (tObj.createTextRange) {
let rng = tObj.createTextRange();
rng.move("character", sPos);
rng.select();
}
});
}
PS:这里要加上nextTick使用,否则光标定位无效。