UNPKG

nimble-ui

Version:
53 lines (50 loc) 1.4 kB
import { callFn } from 'nimble-lib'; /** * 聚焦 * @returns {Object} */ export default function focus () { return { /** * 当元素dom插入到文档中 * @param {HTMLElement} el input/textarea元素 * @param {Object} binding 绑定的值 */ inserted (el, binding) { let _value = (binding && binding.value) || {}; if (_value.autofocus) { _setFocus(el, true); } }, /** * 当元素更新 * @param {HTMLElement} el input/textarea元素 * @param {Object} binding 绑定的值 */ update (el, binding) { binding = binding || {}; let _val = binding.value || {}; let _oldVal = binding.oldValue || {}; if (_val.autofocus !== _oldVal.autofocus) { // update 回调 _setFocus(el, _val.autofocus); } } }; } /** * 设置元素是否focus * @param {HTMLElement} el input/textarea元素 * @param {Boolean} autofocus 是否focus */ function _setFocus (el, autofocus) { if (!el || (el && el === document.activeElement)) { return; } if (autofocus) { el.setAttribute('autofocus', 'autofocus'); callFn(el.focus, [], el); } else { el.removeAttribute('autofocus'); callFn(el.blur, [], el); } }