在使用Element Plus的el-input
组件时,密码输入框的明密文切换是一个常见需求。然而在切换过程中,可能会发现光标的位置并不会自动调整到文本的末尾,而是回到了输入框的首字符。这对用户体验来说是一个不小的困扰。本文将详细介绍如何通过简单的代码调整来优雅地解决这一问题。
Element Plus官网输入框明密文切换时,光标回到首字符:
解决方案
通过使用JavaScript的setSelectionRange
方法,我们可以手动设置光标的位置,确保每次切换后光标都位于文本的末尾。下面是具体实现步骤:
技术栈及其版本:element-plus@2.8.6(vue@3.5.12(typescript@5.4.5))
实现步骤
-
创建template模板
<template> <el-input ref="passwordInputRef" v-model="form.password" placeholder="密码" :maxlength="20" :type="passwordType" > <template #suffix> <SvgIcon @click="togglePassword" :name="passwordType === 'password' ? 'common/password-eyeclose' : 'common/password-eye'" class="text-14 cursor-pointer color-[#a8abb2]" ></SvgIcon> </template> </el-input> </template>
-
TypeScript编写
import { ElInput } from 'element-plus'; /** 密码输入框类型 */ const passwordType = ref('password'); const passwordInputRef = ref<typeof ElInput | null>(null); /** 密码明密文切换 */ const tooglePassword = () => { passwordType.value = passwordType.value === 'password' ? '' : 'password'; const inputElement = passwordInputRef.value?.input as HTMLInputElement; if (inputElement) { const length = inputElement.value.length; // 设置光标位置到文本末尾 -- 需要用 setTimeout setTimeout(() => { inputElement.setSelectionRange(length, length); inputElement.focus(); }); } };
关键步骤解析
-
管理密码类型:使用
ref
来管理passwordType
,初始值为password
,以便动态控制输入框的显示类型。 -
获取输入框引用:通过
ref
获取el-input
组件的引用,以便直接操作原生DOM元素。 -
切换显示状态:在
togglePassword
方法中,切换passwordType
的值,并通过setTimeout
确保在类型切换完成后设置光标位置。 -
设置光标位置:使用
setSelectionRange
方法将光标移动到文本末尾,并使用focus
保持输入框的聚焦状态。
实现效果
细节注意
因密码输入框支持输入中文字符,如若产品需要限制密码为英文、数字、特殊字符,还需要完善一下细节。监听输入框输入事件:@input="onInputPassword"
/** 密码输入:限制英文、数字、字符 */
const onInputPassword = (val: string) => {
if (!val) return
setTimeout(() => {
form.password = val.replace(/[^A-Za-z0-9!@#$%^&*()_+\[\]{};':"\\|,.<>\/?`~\-=\s]/g, '')
}, 0)
}
以上就是输入框明密文切换光标错位问题的解决方法啦^-^