编写一个指令(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))
}
相关推荐
用户6000718191018 分钟前
【翻译】用生成器实现可续充队列
前端
少云清20 分钟前
【UI自动化测试】4_web自动化测试 _元素定位(重点)
前端·web前端自动化
若丶相见28 分钟前
腾讯云完整部署方案:CODING + CI/CD + Docker + Nginx + K8s 扩展
前端·后端
比奇堡鱼贩1 小时前
python第五次作业
开发语言·前端·python
半兽先生1 小时前
使用 retire.js 自动检测前端 JavaScript 库漏洞
开发语言·前端·javascript
扶苏10022 小时前
详解Vue3的自定义 Hooks
前端·javascript·vue.js
二级小助手2 小时前
26年计算机二级web考试介绍【内附真题】
前端·计算机二级·全国计算机二级·web二级·二级web·前端二级·全国计算机web二级
专注VB编程开发20年3 小时前
WebView2 处理跨域访问限制,Frame脚本执行,难度比CEF大10倍
前端·javascript·.net
CHANG_THE_WORLD3 小时前
指针入门一
java·前端·网络
摸鱼仙人~3 小时前
主流前端「语言/技术 → 主流框架 → 组件库生态 → 适用场景」解析
前端