【问题标题】:.class with display: none -> .class:focus with display: block; causes links to not work.class with display: none -> .class:focus with display: block;导致链接不起作用
【发布时间】:2019-06-19 06:36:26
【问题描述】:

我正在尝试创建一个选项菜单。当用户单击一个框时,第一个框内会出现一个带有链接的内框。注意:这个内部(第二个)盒子很重要。单击离开第一个框或单击另一个框将隐藏第一个框的内框。

第二个框中的链接无法打开网页(即使目标设置为 _blank),而是隐藏了内框。

我只能通过使用 :focus 和 display: none -> display: block 来获得显示/隐藏切换内框功能

孤立示例:https://codepen.io/Rogue75/pen/ewdQZq

<div class="container"> 
    <div class="box" tabindex="1">
        <p>Click anywhere in this box.</p>    
        <div class="inner_box">
            <p>Click this <a href="http://google.com" target="_blank">link</a>.</p>
        </div>      
    </div> 
    <!-- REPEATS THE ABOVE TWICE -->
    <div class="box" tabindex="2">
        <p>Click anywhere in this box.</p>    
        <div class="inner_box">
            <p>Click this <a href="http://google.com" target="_blank">link</a>.</p>
        </div>      
    </div>    
    <div class="box" tabindex="3">
        <p>Click anywhere in this box.</p>    
        <div class="inner_box">
            <p>Click this <a href="http://google.com" target="_blank">link</a>.</p>
        </div>      
    </div>    
    <!-- NO HIDE BELOW -->    
    <div class="nohide_box" tabindex="3">
        <p><B>This box doesn't show/hide anything.</p>
        <div class="nohide_inner_box">
            <p>Click this <a href="http://google.com" target="_blank">link</a> which works.</p>
        </div>
    </div> 
</div>
.container {

}

.box, .nohide_box {
  padding: 20px;
  border: 1px solid black;
  float: left;
  background-color: pink;
}

.inner_box {
  display: none;
  background-color: wheat;
  padding: 10px 0;
}

.box:focus .inner_box {
  display: block;
}

.nohide_box {
  background-color: lightgreen !important;
}

链接应该可以工作,理想情况下内框会保持原样,但是链接不起作用并且内框会隐藏。我的目标是:

  • 让这些框 (div) 在点击时显示一个内框 (div)
  • 点击离开或点击另一个隐藏内框的框时
  • 在内框 (div) 内部存在一个功能链接,该链接在单击后保持内框可见。

理想情况下,这一切只使用 HTML 和 CSS 即可完成,但在这一点上,我对一些低税脚本持开放态度。

【问题讨论】:

标签: html css


【解决方案1】:

不知道这是否适用于您的用例,但您可以通过将 CSS 更改为以下内容来“欺骗”它:

.box:focus .inner_box,
.box:focus-within .inner_box,
.inner_box:hover {
  display: block;
}

所以只要你的鼠标仍然悬停在 div 上,盒子就不会关闭。

已根据 OP 评论更新: 考虑使用 :focus-within:focus 以保持 Div 可见,只要某些子元素具有焦点(在 Edge 中不起作用 然而https://caniuse.com/#feat=css-focus-within)

【讨论】:

  • 感谢您的建议。它适用于 codepen 示例,但不适用于我的实际部署。我会继续修改它并回复你。
  • 看起来像在同一显示器上使用 .box:focus, .box:focus-within 所涉及的技巧:块样式。现在聚焦在其中的对象将触发相同的事件!感谢您引导我进行修复。请更新您的答案,我会将其标记为正确。
猜你喜欢
  • 2017-12-02
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2023-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多