focus-within 适用于 Android 浏览器,但不适用于 iOS

Cha*_*lie 2 css iphone safari ios

我有一个使用 :focus-within 伪类实现的两级导航菜单。在小型设备上,它应显示为屏幕底部的“菜单”按钮,点击后会展开到第一级。第二级应该在点击第一级项目时打开,并且第一级应该(当然)保持打开状态。这在 Android 手机上运行良好,但我的 iPhone 用户报告菜单按钮对点击没有响应。

这是 HTML 片段:

<div class="gcc-expands" id="GCCmainNav">
    <a href="#" id="GCCnavOpen">&#9776; Menu</a>
    <div class="gcc-expansion">
        <nav role="navigation"class="gcc-menu">
            <a href="/">Home</a>
            <a href="/#GCCprogramme">Concerts&nbsp;&amp;&nbsp;Events</a>
            <div class="gcc-expands">
                <a href="#">About&nbsp;Us</a>
                <div class="gcc-expansion">
                    <div class="gcc-menu" id="GCCaboutNav">
                        <a href="/about-us.php">The Choir</a>
                        <a href="/#GCCrecordings">The Choir on CD</a>
                        <a href="/history.php">History</a>
                        <a href="/contact-us.php#GCCcontact">Contact</a>
                    </div>
                </div>
            </div>
            <a href="/for-members/members1.php">For&nbsp;Members</a>
        </nav>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是 CSS:

.gcc-expands {
    position: relative;
}

.gcc-expansion {
    display: none;
    position: relative;
}

.gcc-expands:focus-within>.gcc-expansion {
    display: block;
}
Run Code Online (Sandbox Code Playgroud)

关注 #GCCnavOpen 伪链接应会导致显示第一级 .gcc-expansion,然后关注“关于我们”链接应保持第一级打开 (:focus-within) 并打开内部 .gcc-expansion。

根据 caniuse 的说法,自 10.3(2017)以来,iOS Safari 就支持此功能,但它似乎对我的用户不起作用。请问有什么见解吗?

Cha*_*lie 5

我已经破解了这个。

我猜测,由于某种原因,这些元素在点击时没有获得焦点。因此,点击我的“菜单”链接并没有赋予该元素焦点,因此 :focus-within 无法在父级中操作。这似乎是 iOS 在纯触摸界面上的一个“功能”;在 Windows 或 Andoid 环境(或 MacOS)中这不是问题。

我发现解决方法是向菜单层次结构中的每个链接添加显式内容tabindex="0"(包括充当按钮的伪链接)。这似乎使得该元素可以在 iOS 触摸界面中聚焦。

为了清楚起见,下面是工作 HTML(CSS 没有改变):

<div class="gcc-expands" id="GCCmainNav">
    <a href="#" tabindex="0" id="GCCnavOpen">&#9776; Menu</a>
    <div class="gcc-expansion">
        <nav role="navigation"class="gcc-menu">
            <a href="/" tabindex="0">Home</a>
            <a href="/#GCCprogramme" tabindex="0">Concerts&nbsp;&amp;&nbsp;Events</a>
            <div class="gcc-expands">
                <a href="#" tabindex="0">About&nbsp;Us</a>
                <div class="gcc-expansion">
                    <div class="gcc-menu" id="GCCaboutNav">
                        <a href="/about-us.php" tabindex="0">The Choir</a>
                        <a href="/#GCCrecordings" tabindex="0">The Choir on CD</a>
                        <a href="/history.php" tabindex="0">History</a>
                        <a href="/contact-us.php#GCCcontact" tabindex="0">Contact</a>
                    </div>
                </div>
            </div>
            <a href="/for-members/members1.php" tabindex="0">For&nbsp;Members</a>
        </nav>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

当然,还有一堆辅助 CSS 来定位和设置两级菜单的样式。我没有在这里发布它,因为它是特定于设计的,与问题无关。

我希望这能帮助其他一些挣扎的灵魂。