编写一个指令(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))
}
相关推荐
kyriewen9 分钟前
我扒了 npm 三年数据:AI 没把依赖变胖,是把包变多了
前端·人工智能·程序员
SensorFlow26 分钟前
曝光埋点别放在组件渲染里:连续可见与去重范围怎么验收
javascript
harris148154352975827 分钟前
能解码不等于能信任:JWT 的签名到底验的是什么
javascript
liqingdi43727 分钟前
[SWPUCTF 2023 秋季新生赛]Easy SMC
服务器·前端·javascript
用户873598656358732 分钟前
为什么 greedy 也可能出不同 token,MoE 为什么更严重
前端
日耗10亿Token被老板赶出门32 分钟前
REA 火了:一个 Electron 按钮的调用链,它能追到哪一步?
javascript·electron
Gizzap_Tech33 分钟前
多语言官网如何兼顾统一与本地化?从页面生成到语言切换
前端
IT_陈寒34 分钟前
Java缓存踩坑记:明明设置了过期时间,怎么还是读到脏数据?
前端·人工智能·后端
靠coding维持生计的potato34 分钟前
使用 unified diff 为 pnpm 依赖编写可复现补丁
前端
Initialize-le1 小时前
systemd 服务起不来?五步排查法
前端·chrome