编写一个指令(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))
}
相关推荐
求知若渴,虚心若愚。7 分钟前
Error reading config file (/home/ansible.cfg): ‘ACTION_WARNINGS(default) = True
linux·前端·ansible
LinDaiuuj1 小时前
最新的前端技术和趋势(2025)
前端
paopaokaka_luck1 小时前
婚纱摄影管理系统(发送邮箱、腾讯地图API、物流API、webSocket实时聊天、协同过滤算法、Echarts图形化分析)
vue.js·spring boot·后端·websocket·算法·echarts
一只小风华~1 小时前
JavaScript 函数
开发语言·前端·javascript·ecmascript·web
程序猿阿伟2 小时前
《不只是接口:GraphQL与RESTful的本质差异》
前端·restful·graphql
仰望星空的凡人3 小时前
【JS逆向基础】数据库之MongoDB
javascript·数据库·python·mongodb
若梦plus4 小时前
Nuxt.js基础与进阶
前端·vue.js
樱花开了几轉4 小时前
React中为甚么强调props的不可变性
前端·javascript·react.js
风清云淡_A4 小时前
【REACT18.x】CRA+TS+ANTD5.X实现useImperativeHandle让父组件修改子组件的数据
前端·react.js
小飞大王6664 小时前
React与Rudex的合奏
前端·react.js·前端框架