编写一个指令(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))
}
相关推荐
qq834431013 分钟前
一款纯前端的excel控件,XuY_Sheet 电子表格组件教程
前端·excel·教程·luckysheet·xuy_sheet控件·前端表格控件
云浪16 分钟前
从 0 到实战:掌握向量数据库 Milvus,构建 AI 应用的核心能力
javascript·数据库·人工智能
不爱说话郭德纲31 分钟前
零基础,学做KMP项目,TRAE Work手把手带你月薪.....
前端·后端·app
敲代码的玉米C1 小时前
Agent 做 IDE
前端·人工智能·开源
鹏北海1 小时前
AI 全栈时代的多语言 SDK 版本管理:认识 mise
前端·后端
下山1 小时前
别再手切终端管 Agent 了!1 个 Skill 监督多个主流 CLI,默认每 15 秒读屏(建议收藏)🚀
前端·ai编程
飘逸啊1 小时前
分而治之:关注点分离在Android与React中的架构实践与对比
前端
算法解题那些事1 小时前
前端暑期实习面经(网上收集)
前端
敲代码的玉米C1 小时前
补 322 个测试,挖出 19 个 bug
前端·人工智能·架构
敲代码的玉米C1 小时前
怎么让 Agent 没法假装自己成功了
前端·人工智能·架构