
如何节省精力地为 input 启用焦点定位?
在项目中经常需要在获取 Input 焦点时将光标置于右侧末尾,一个通用的解决方案可以节省大量的修改工作。
自定义指令
我们可以全局定义一个自定义指令来实现这一功能:
Vue.directive('focus-right', {
inserted: function (el) {
el.addEventListener('focus', function () {
const length = el.value.length;
setTimeout(() => {
el.selectionStart = length;
el.selectionEnd = length;
});
});
}
});
登录后复制
然后在组件中使用:
<input v-focus-right>
登录后复制
插件
也可以创建一个插件:
const FocusRightPlugin = {
install(Vue) {
Vue.prototype.$inputFocusRight = function (e) {
const input = e.target;
const length = input.value.length;
setTimeout(() => {
input.selectionStart = length;
input.selectionEnd = length;
});
};
}
};
// 在 main.js 中
import FocusRightPlugin from './focusPlugin';
Vue.use(FocusRightPlugin);
// 组件中使用
<input @focus="$inputFocusRight">
登录后复制
以上就是如何高效地使 Input 焦点定位到右侧末尾?的详细内容,更多请关注米云其它相关文章!
