编写一个指令(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))
}
相关推荐
Highcharts.js9 分钟前
Highcharts Dashboards 官方文档|如何创建第一个看板
前端·开发文档·仪表板·highcharts·创建看板
小明记账簿15 分钟前
解锁前端新技能:让JavaScript与CSS变量共舞
前端·javascript·css
pyniu19 分钟前
redis day1
java·前端·spring
b***748827 分钟前
从技术复杂度到体系竞争力:2026 年前端发展的全新范式转移
前端
IT_陈寒31 分钟前
Java并发编程避坑指南:这5个隐藏陷阱让你的性能暴跌50%!
前端·人工智能·后端
化作繁星31 分钟前
前端设计模式详解
前端·设计模式
jinxinyuuuus39 分钟前
快手在线去水印:短链解析、API逆向与视频流的元数据重构
前端·人工智能·算法·重构
棒棒的唐43 分钟前
avue uploader图片预览拉伸变型的css处理方法
前端·css
sunshine~~~44 分钟前
ROS 2 Jazzy + Python 3.12 + Web 前端案例
开发语言·前端·python·anaconda·ros2
古韵1 小时前
如何从Axios平滑迁移到Alova
vue.js·react.js·node.js