编写一个指令(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))
}
相关推荐
buhuimaren_6 分钟前
系统安全及运用
前端·chrome
littlegirll9 分钟前
一个KADB报错分析及实验
java·javascript·数据库
什么问题10 分钟前
记一次 VisionPro +PlayMaker 项目修正
开发语言·前端·javascript
新缸中之脑13 分钟前
Chrome 146:终结专用AI浏览器?
前端·人工智能·chrome
fjh199722 分钟前
通过配置 Edge 浏览器 DoH 和 ECH 实现特定网站如linuxdo裸连访问
前端·edge
北城笑笑30 分钟前
Vue 99 ,Vue 项目代理配置规范:跨域解决、路径重写与多环境适配最佳实践( 企业级避坑指南 )
运维·前端·nginx·vue
梵得儿SHI31 分钟前
Vue3 实战:从 0 搭建企业级后台管理系统(Router+Pinia+Axios+Element Plus 全整合)
前端·javascript·vue.js·pinia状态管理·项目初始化·页面路由配置·后台首页布局
不能只会打代码33 分钟前
基于Vue 3 + Spring Boot的物联网生鲜品储运系统设计与实现(源码附有详细的文档讲解)
java·前端·vue.js·spring boot·后端·物联网·github
A923A34 分钟前
【Vue3大事件 | 项目笔记】第三天
前端·vue.js·笔记·vue·前端项目
Smoothcloud润云37 分钟前
告别 Selenium:Playwright 现代 Web 自动化测试从入门到实战
前端·人工智能·selenium·测试工具·架构·自动化