编写一个指令(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))
}
相关推荐
sp425 分钟前
通过 RootEncoder 进行安卓直播 RTSP 推流
前端
_院长大人_6 分钟前
构建一个 Vue 基于el-input的磨损区间选择器组件 —— WearRangeSelector
前端·javascript·vue.js
遗憾随她而去.7 分钟前
前端 Vue 虚拟列表(Virtual List),从原理到实战
前端·javascript·vue.js
tangdou3690986557 分钟前
图文并茂手把手教你Claude Code 多智能体 Agent Teams,一人变团队
前端·后端·ai编程
看客随心11 分钟前
element-ui table表格 tr间距\行间距设置
vue.js·ui·elementui
工边页字13 分钟前
图文教学,服务端如何发送(钉钉 +飞书 )机器人通知
java·前端·后端
竹林81816 分钟前
从零集成RainbowKit:我如何解决多链钱包连接中的“幽灵网络”问题
前端·javascript
前端炒粉16 分钟前
Webpack 基础核心内容总结
前端·webpack·node.js
光影少年17 分钟前
前端安全问题?XSS和CSRF?
前端·安全·xss
小小小小宇19 分钟前
RSA攻略
前端