编写一个指令(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))
}
相关推荐
一只蝉nahc20 分钟前
vue使用iframe内嵌unity模型,并且向模型传递信息,接受信息
前端·vue.js·unity
状元岐41 分钟前
C#反射从入门到精通
java·javascript·算法
子兮曰1 小时前
Bun v1.3.12 深度解析:新特性、性能优化与实战指南
前端·typescript·bun
2401_885885042 小时前
易语言彩信接口怎么调用?E语言Post实现多媒体数据批量下发
前端
a1117762 小时前
Three.js 的前端 WebGL 页面合集(日本 开源项目)
前端·javascript·webgl
Kk.08022 小时前
项目《基于Linux下的mybash命令解释器》(一)
前端·javascript·算法
程序员鱼皮2 小时前
又一个新项目开源,让 AI 帮你盯全网热点!
javascript·ai·程序员·编程·ai编程
MXN_小南学前端2 小时前
前端开发中 try...catch 到底怎么用?使用场景和最佳实践
javascript·vue.js
星空椰3 小时前
JavaScript 基础进阶:分支、循环与数组实战总结
开发语言·javascript·ecmascript
小李子呢02113 小时前
前端八股---闭包和作用域链
前端