编写一个指令(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))
}
相关推荐
PTC17 分钟前
做了个 EPUB 阅读器,被「阅读进度同步」折磨了一周,总结 4 个血泪教训
前端
Aaron_Feng32 分钟前
适配Swift 6 Sendable:用AALock优雅解决线程安全与不可变引用难题
前端
2301_7965125244 分钟前
【精通篇】打造React Native鸿蒙跨平台开发高级复合组件库开发系列:Swipe 轮播(用于循环播放一组图片或内容)
javascript·react native·react.js·ecmascript·harmonyos
大时光1 小时前
gsap 配置解读 --7
前端
念念不忘 必有回响1 小时前
前端判断文本是否溢出:单行与多行场景的完整解析
前端·javascript·css·vue.js
css趣多多2 小时前
vue3的组件间通信ref子组件需要把父组件要的ref数据开放
前端·javascript·vue.js
我是伪码农2 小时前
Vue 2.10
前端·javascript·vue.js
AAA阿giao2 小时前
React 性能优化双子星:深入、全面解析 useMemo 与 useCallback
前端·javascript·react.js
不想秃头的程序员2 小时前
父传子全解析:从基础到实战,新手也能零踩坑
前端·vue.js·面试
大时光2 小时前
gsap 配置解读 --5
前端