useFocusWithin

监听当前焦点是否在某个区域之内,同 css 属性 :focus-withinopen in new window

代码演示

基础用法


isFocusWithin: false

-
点击查看代码
<script setup>
import { useFocusWithin } from "ahooks-for-vue";
import { ref } from "vue";

const domRef = ref(null);
const { isFocusWithin, stop, restart } = useFocusWithin(domRef);
</script>
<template>
  <div>
    <div
      ref="domRef"
      :style="{
        padding: '32px',
        backgroundColor: isFocusWithin ? 'red' : '',
        border: '1px solid gray',
        userSelect: 'none',
      }"
    >
      <label :style="{ display: 'block' }"> First Name: <input /> </label><br />
      <label :style="{ display: 'block', marginTop: 16 }">
        Last Name: <input />
      </label>
    </div>
    <p>isFocusWithin: {{ isFocusWithin }}</p>
    <button @click="restart">重新开始监听</button>
    -
    <button @click="stop">移除监听</button>
  </div>
</template>
<style></style>

传入 DOM 元素

API

const isFocusWithin = useFocusWithin(target, {
  onFocus,
  onBlur,
  onChange,
});

Params

参数说明类型默认值
targetDOM 节点或者 Ref 对象() => Element | Element | Ref<Element>-
options额外的配置项Options-

Options

参数说明类型默认值
onFocus获取焦点时触发(e: FocusEvent) => void-
onBlur失去焦点时触发(e: FocusEvent) => void-
onChange焦点变化时触发(isFocusWithin: boolean) => void-

Result 相比ahooks新增的APi

参数说明类型
isFocusWithin焦点是否在当前区域Ref<boolean>
restart重新开始监听函数() => void
stop移除监听函数() => void
Last Updated:
Contributors: 郑磊