
最近公司做移动端,用手点击时光标定位到最后一位。
具体代码
这是使用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使用,否则光标定位无效。
本文介绍如何在移动端使用Vue.js和van-field组件时,通过v-for循环实现列表中每个输入框在获取焦点时自动将光标定位到最后一位,包括处理无ID情况和使用Vue.nextTick确保定位效果。
2447

被折叠的 条评论
为什么被折叠?



