diff --git a/themes/gitbook/components/NavPostItem.js b/themes/gitbook/components/NavPostItem.js index 0110be776f0..46664a56983 100644 --- a/themes/gitbook/components/NavPostItem.js +++ b/themes/gitbook/components/NavPostItem.js @@ -1,6 +1,7 @@ import Badge from '@/components/Badge' import Collapse from '@/components/Collapse' import { siteConfig } from '@/lib/config' +import { useEffect, useState } from 'react' import CONFIG from '../config' import BlogPostCard from './BlogPostCard' @@ -13,17 +14,32 @@ import BlogPostCard from './BlogPostCard' */ const NavPostItem = props => { const { group, expanded, toggleItem } = props // 接收传递的展开状态和切换函数 - // const [isOpen, setIsOpen] = useState(expanded) // 使用展开状态作为组件内部状态 const hoverExpand = siteConfig('GITBOOK_FOLDER_HOVER_EXPAND', false, CONFIG) + const [isTouchDevice, setIsTouchDevice] = useState(false) + + // 检测是否为触摸设备 + useEffect(() => { + const checkTouchDevice = () => { + if (window.matchMedia('(pointer: coarse)').matches) { + setIsTouchDevice(true) + } + } + checkTouchDevice() + + // 可选:监听窗口大小变化时重新检测 + window.addEventListener('resize', checkTouchDevice) + return () => { + window.removeEventListener('resize', checkTouchDevice) + } + }, []) // 当展开状态改变时触发切换函数,并根据传入的展开状态更新内部状态 const toggleOpenSubMenu = () => { toggleItem() // 调用父组件传递的切换函数 - // setIsOpen(!expanded) // 更新内部状态为传入的展开状态的相反值 } const onHoverToggle = () => { // 允许鼠标悬停时自动展开,而非点击展开 - if (!hoverExpand) { + if (!hoverExpand || isTouchDevice) { return } toggleOpenSubMenu()