【Element Plus】输入框明密文切换光标错位问题

在使用Element Plus的el-input组件时,密码输入框的明密文切换是一个常见需求。然而在切换过程中,可能会发现光标的位置并不会自动调整到文本的末尾,而是回到了输入框的首字符。这对用户体验来说是一个不小的困扰。本文将详细介绍如何通过简单的代码调整来优雅地解决这一问题。

Element Plus官网输入框明密文切换时,光标回到首字符:

解决方案

通过使用JavaScript的setSelectionRange方法,我们可以手动设置光标的位置,确保每次切换后光标都位于文本的末尾。下面是具体实现步骤:

技术栈及其版本:element-plus@2.8.6(vue@3.5.12(typescript@5.4.5))

实现步骤

  1. 创建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>
  2. 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();
        });
      }
    };

关键步骤解析

  1. 管理密码类型:使用ref来管理passwordType,初始值为password,以便动态控制输入框的显示类型。

  2. 获取输入框引用:通过ref获取el-input组件的引用,以便直接操作原生DOM元素。

  3. 切换显示状态:在togglePassword方法中,切换passwordType的值,并通过setTimeout确保在类型切换完成后设置光标位置。

  4. 设置光标位置:使用setSelectionRange方法将光标移动到文本末尾,并使用focus保持输入框的聚焦状态。

实现效果

细节注意

因密码输入框支持输入中文字符,如若产品需要限制密码为英文、数字、特殊字符,还需要完善一下细节。监听输入框输入事件:@input="onInputPassword"

/** 密码输入:限制英文、数字、字符 */
const onInputPassword = (val: string) => {
  if (!val) return
  setTimeout(() => {
    form.password = val.replace(/[^A-Za-z0-9!@#$%^&*()_+\[\]{};':"\\|,.<>\/?`~\-=\s]/g, '')
  }, 0)
}

以上就是输入框明密文切换光标错位问题的解决方法啦^-^ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值