编写一个指令(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))
}
相关推荐
听风说图1 分钟前
Figma画布协议揭秘:组件实例的SymbolOverrides覆盖机制
前端·canvas
小杨前端4 分钟前
前端如何自己实现一个webpack的热更新?
前端
@大迁世界6 分钟前
02.CSS变量 (Variables)
前端·css
鹏多多9 分钟前
轻量+响应式!React瀑布流插件react-masonry-css的详细教程和案例
前端·javascript·react.js
用户3458482850512 分钟前
java中的tomicInteger/AtomicLong介绍
前端·后端
一颗宁檬不酸14 分钟前
Vue.js 初学者基础知识点总结 第一弹
前端·javascript·vue.js
xiaoxue..16 分钟前
解析 LocalStorage与事件委托在前端数据持久化中的应用
前端·javascript·面试
Mintopia16 分钟前
「无界」全局浮窗组件设计与父子组件最佳实践
前端·前端框架·前端工程化
j***894616 分钟前
MySQL数据的增删改查(一)
android·javascript·mysql
@cc小鱼仔仔29 分钟前
vue 知识点
前端·javascript·vue.js