编写一个指令(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))
}
相关推荐
果然_9 分钟前
纯前端图片压缩怎么做?不用上传服务器,浏览器里跑完所有逻辑
前端
英勇无比的消炎药11 分钟前
TinyRobot DropdownMenu 下拉菜单:三种触发方式与实现原理
vue.js
Csvn18 分钟前
🖼️ OffscreenCanvas:把 Canvas 绘制搬出主线程,动画卡顿的终极解药
前端
用户693717500138418 分钟前
了解一下 Agent Harness
android·前端·后端
swipe31 分钟前
16|(前端转全栈)前端人排查后端问题:curl、traceId、日志、MySQL、Redis 怎么用?
前端·后端·面试
anyup35 分钟前
uni-app 没有根组件?仅需几行代码实现全局 Toast 和 Modal
前端·架构·uni-app
并不喜欢吃鱼44 分钟前
一.前端web开发:零基础吃透 HTML5 核心知识
前端·html·html5
Hilaku1 小时前
前端真的比后端简单吗?
前端·javascript·程序员
Canace1 小时前
为了给视频里的人脸打码,我让 Claude 做了个 Skill
前端·人工智能