编写一个指令(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 小时前
副队长Vue3教程(2)--Vite 搭建 Vue 项目,认识目录结构
前端·javascript·vue.js·vite·创建项目·目录结构·项目结构
濮水大叔1 小时前
Cabloy/Zova 与 Next.js 的 SSR 水合差异
前端·typescript·next.js
SoaringHeart2 小时前
Flutter最佳实践:用 flutter_html 渲染富文本
前端·flutter
Flynt3 小时前
Chrome给AI编程助手塞了203篇前端规范,我拆包实测:检索0.77秒是真快,扫描器有点挑食
前端·chrome·ai编程
北城笑笑3 小时前
Vue 110 ,若依SSE流式接口限次空500排查与解决
前端·javascript·vue.js·后端·vue
程序员韩星4 小时前
OpenAI 兼容接口返回 404,先查请求地址,再查模型名
前端·人工智能·http
Patrick_Wilson4 小时前
构建通过了,为什么有些浏览器还会白屏?
前端·javascript·浏览器
其实防守也摸鱼4 小时前
用 Claude Code 重构遗留系统:从评估到落地的完整指南
前端·网络·人工智能·chrome·安全·重构
七仔啊5 小时前
CNC计算机数控加工模拟器
前端
张一凡935 小时前
你的 AGENTS.md,真的管到模型写代码了吗?
前端·后端·agent