在網(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 }}
新聞熱點
疑難解答
圖片精選