编写一个指令(v-focus2end)使输入框文本在聚焦时焦点在文本最后一个位置

项目反馈输入框内容比较多时候,让鼠标光标在最后一个位置,心想什么奇葩需求,后面试了一下,是有点影响体验,于是就有了下面的效果,我目前的项目都是若依的架子,用的是vue2版本。vue3的朋友想要使用,自行调节

效果图如下:
使用方法:
  • 前提是指令被注册,代码不显示注册内容
javascript 复制代码
<el-input v-focus2end v-model="dialog.form.actionSign" placeholder="请输入" clearable />
v-focus2end 指令
  • 还能继续优化,我就不想在操作了
javascript 复制代码
/**
 * Copyright ©
 * # v-focus2end
 * @author: zw
 * @date: 2023-07-17
 */

export default {
  inserted(el) {
    const input = el instanceof HTMLInputElement ? el : el.querySelector('input')

    input.addEventListener('focus', focusEventListener.bind(input), false)
    input.addEventListener('blur', blurEventListener.bind(input), false)

    el.__focusEventListener = focusEventListener
    el.__blurEventListener = blurEventListener
  },
  unbind(el) {
    const input = el instanceof HTMLInputElement ? el : el.querySelector('input')

    input.removeEventListener('focus', el.__focusEventListener, false)
    input.removeEventListener('blur', el.__blurEventListener, false)
  },
}

function focusEventListener(e) {
  e.preventDefault()
  setTimeout(() => {
    const inputLength = this.value.length
    this.setSelectionRange(inputLength, inputLength)
    smoothMove.call(this)
  }, 300)
}

function blurEventListener() {
  this.removeEventListener('focus', focusEventListener, false)
}

function smoothMove() {
  const scrollMax = this.scrollWidth - this.clientWidth
  const duration = 300
  const startTime = performance.now()

  function smoothScroll(timestamp) {
    const elapsedTime = timestamp - startTime
    const progress = Math.min(elapsedTime / duration, 1)

    const scrollPosition = progress * scrollMax
    this.scrollLeft = scrollPosition

    if (elapsedTime < duration) {
      requestAnimationFrame(smoothScroll.bind(this))
    }
  }

  requestAnimationFrame(smoothScroll.bind(this))
}
相关推荐
YiWait14 小时前
基于 Vue 3 的网络收音机,编译为桌面应用软件
前端·javascript·vue.js
虾壳云官方14 小时前
OpenClaw 绑定企业微信完整指南
服务器·前端·网络·人工智能·企业微信·open claw·小龙虾
MichaelJohn14 小时前
别卷框架了!前端人,用 JS + LangChain + DeepSeek 开启你的 AI 转型第一步
前端
古法编程第一人14 小时前
使用Electric同步前后端数据
前端·vue.js
Fisschl14 小时前
在 Vue 中实现输入框@人功能
vue.js
朱涛的自习室14 小时前
30天11万行代码,我用 Trae 和 Gemini 造了个 AI 测试引擎
android·前端·人工智能
大连好光景14 小时前
登录凭证 | Session+Cookie | Redis Token | JWT
前端·javascript
deepin_sir14 小时前
11 - 模块与包
前端·数据库·python
小小小小宇15 小时前
前端 Redux applyMiddleware 中间件链原理
前端
英俊潇洒美少年15 小时前
Vue 生产环境打包:SourceMap、压缩、混淆、Gzip、多环境配置 企业级最佳实践
前端·javascript·vue.js