国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue-auto-focus: 控制自動聚焦行為的 vue 指令方法

2024-05-06 15:31:12
字體:
供稿:網(wǎng)友

在網(wǎng)頁的表單中,經(jīng)常需要用程序來控制input和textarea的自動聚焦行為。例如我最近做的一個項目,有個裝箱出庫的流程,input框自動聚焦的流程如下:頁面進入時自動聚焦到訂單號輸入框->訂單號掃描完畢聚焦到商品條碼輸入框->掃描完一個商品條碼后依然停留在條碼輸入框->所有條碼掃描完畢聚焦到訂單號輸入框。

為了應(yīng)付這種需求,就做了這個指令,github地址: vue-auto-focus ,歡迎star。

example

<template> <form v-auto-focus="focusCtrl" :data-current="currentIndex" :data-action="actionType">  <input @focus="setFocusIndex(0)" type="text" data-index="0">  <input @focus="setFocusIndex(1)" type="text" data-index="1">  <textarea @focus="setFocusIndex(2)" name="" id="" cols="30" rows="10" data-index="2"></textarea>  <input @focus="setFocusIndex(3)" type="text" data-index="3"> </form></template><style scoped></style><script type="text/babel"> export default {  data() {   return {    focusCtrl: 0, // 自動聚焦控制,變動時,執(zhí)行自動聚焦指令    currentIndex: 0, // 當前聚焦元素的索引    actionType: 'next', // 自動聚焦的行為類型   }  },  methods: {   /**    * 控制自動聚焦指令執(zhí)行    * @param actionType {string} 自動聚焦類型 it can be 'next'/'prev'/'first'/'last'/'jump'    * @param index {string} 當actionType為'jump'時,需要傳入將要聚焦元素的索引    **/   setFocus(actionType,index) {    if (actionType === 'jump') {     this.currentIndex = index    }    this.focusCtrl++    this.actionType = actionType   },   /**    * 元素聚焦時,獲取當前聚焦元素的索引    * @param index {number} 當前聚焦的索引    **/   setFocusIndex(index) {    this.currentIndex = index   },  } }</script>

行為控制

next 聚焦到下一個元素

prev 聚焦到上一個元素

first 聚焦到第一個元素

last 聚焦到最后一個元素

jump 聚焦到指定的元素

聚焦行為控制邏輯

/** * 聚焦行為控制 * next 聚焦到下一個元素 * prev 聚焦到上一個元素 * first 聚焦到第一個元素 * last 聚焦到最后一個元素 * jump 跳轉(zhuǎn)到指定的元素 * @param el */const focusCtrl = function (el) { const action = el.dataset.action const allFocusEls = getAllFocusEls(el) const focusLen = allFocusEls.length let current = getTargetIndex(el,allFocusEls) switch (action) {  case 'next': // 如果action為next,則聚焦到下一個輸入框   if (current >= focusLen - 1) {    current = focusLen - 1   } else {    current++   }   autoFocus(allFocusEls[current])   break  case 'prev': // 如果action為prev,則聚焦到上一個輸入框   if (current <= 0) {    current = 0   } else {    current--   }   autoFocus(allFocusEls[current])   break  case 'first': // 如果為first,則聚焦到第一個輸入框   current = 0   autoFocus(allFocusEls[current])   break;  case 'last': // 如果為last,則聚焦到最后一個輸入框   current = focusLen - 1   autoFocus(allFocusEls[current])   break  case 'jump': // 如果為jump,則獲取focusIndex,跳轉(zhuǎn)到對應(yīng)的輸入框   if (current >= 0 && current < focusLen) {    autoFocus(allFocusEls[current])   }   break }}            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 库车县| 安多县| 永仁县| 日照市| 犍为县| 华容县| 微博| 合山市| 墨竹工卡县| 改则县| 宜春市| 于都县| 临泉县| 禹城市| 柳河县| 台北县| 阿鲁科尔沁旗| 唐河县| 勐海县| 阿拉善右旗| 宜都市| 宁蒗| 桐乡市| 建阳市| 广宁县| 潞城市| 德令哈市| 洛宁县| 衡阳市| 德清县| 济宁市| 疏附县| 龙南县| 通道| 铜川市| 柳河县| 益阳市| 六盘水市| 民勤县| 泗阳县| 含山县|