在<a> element as a child

时间:2017-05-05 03:04:49

标签: javascript jquery html css

So I was modifying HTML to make drop down panels in order to minimize use of JavaScript.

.nav-link {
  border: 1px solid black;
  margin: 10px;
  text-decoration: none;
}

.panel-link {
  display: none;
  position: absolute;
}
.nav-link:hover .panel-link {
  display: block;
}
<nav class="nav">
  <a href="withoutchild.html" class="nav-link">
     <span>Without Child</span>
     <nav class="panel-link">
        <h1>Works</h1>
     </nav>
  </a>
  <a href="withchild.html" class="nav-link">
     <span>With Child</span>
     <nav class="panel-link">
        <a>Not Works</a>
     </nav>
  </a>
</nav>

When you hover both of them, you notice that only the first link opens its drop down panel when you hover it. However, with the second link (Which was layed out exactly the same), it did not because it had a link element as the child. When I view the inspector of Chrome, I realized the '.panel-link' element moved out of the '.nav-link' element, and is now a sibling of '.nav-link'. which looked just like this:

<nav class="nav">
    <a href="withoutchild.html" class="nav-link">
       <span>Without Child</span>
       <nav class="panel-link">
          <h1>Works</h1>
       </nav>
    </a>
    <a href="withchild.html" class="nav-link">
       <span>With Child</span>
    </a>
    
    <!-- This element is moved outside its parent -->
    <nav class="panel-link">
          <a>Not Works</a>
    </nav>
 </nav>

2 个答案:

答案 0 :(得分:2)

嵌套<a>(锚标记)是非法的,会导致无法恢复的错误。

简单地说,浏览器会忽略嵌套<a>的所有内容,直到它们符合此标记的末尾(</a>),用于关闭父<a>标记。

使用您选择的HTML验证程序获取更多详细信息。我使用issue on Github

答案 1 :(得分:0)

我认为问题是您在父<a>代码中有<a>标记。

我不确定你想要的<h1>文字/链接是什么样的,所以无论如何都要保留它。使用CSS,悬停div可以显示另一个div。

.panel-link {
  border: 1px solid black;
  margin: 10px;
  text-decoration: none;
}

.nav-link {
  position: relative;
  display: inline-block;
}

.nav-link-content {
  display: none;
  position: absolute;
  z-index: 1;
}

.nav-link-content a {
  color: black;
  padding: 2px 16px;
  display: block;
}

.nav-link-content a:hover {
  background-color: #fff000
}

.nav-link:hover .nav-link-content {
  display: block;
}
<nav class="nav">
  <div class="nav-link">
    <a href="withoutchild.html" class="panel-link"><span>Without Child</span></a>
    <div class="nav-link-content">
      <h1>Works</h1>
    </div>
  </div>
  <div class="nav-link">
    <a href="withchild.html" class="panel-link"><span>With Child</span></a>
    <div class="nav-link-content">
      <a href="child1.html">Child 1</a>
      <a href="child2.html">Child 2</a>
      <a href="child3.html">Child 3</a>
    </div>
  </div>
</nav>

相关问题