是否可以包装 <a>
标记 <div>
就像这样:
<a href=etc etc>
<div class="layout">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
</div>
</a>
Eclipse 告诉我 div 的位置不对? 如果这是不允许的。我怎样才能使整个“布局”类成为一个链接?
最佳答案
该结构在 HTML5 中是有效的,因为在 HTML5 中, anchor 几乎可以包装除其他 anchor 和表单控件之外的任何元素。现在大多数浏览器都支持这一点,并将问题中的代码解析为有效的 HTML。下面的答案写于 2011 年,如果您支持旧版浏览器(*咳* Internet Explorer *咳*),可能会有用。
没有 HTML5 解析器的旧浏览器(比如 Firefox 3.6)仍然会对此感到困惑,并可能弄乱 DOM 结构。
HTML4 的三个选项 - 使用所有内联元素:
<a href=etc etc>
<span class="layout">
<span class="title">
Video Type
<span class="description">Video description</span>
</span>
</span>
</a>
然后使用 display: block
设置样式
使用 JavaScript 和 :hover
:
<div class="layout">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
</div>
并且(假设 jQuery)
$('.layout').click(function(){
// Do something
}):
和
.layout:hover {
// Hover effect
}
或者最后使用绝对定位放置一个带有CSS的a
anchor 覆盖整个.layout
<div class="layout">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
<a class="more_link" href="somewhere">More information</a>
</div>
和 CSS:
.layout {
position: relative;
}
.layout .more_link {
position: absolute;
display: block;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-indent: -9999px;
z-index: 1000;
}
当然,这不适用于旧版本的 IE。
关于javascript - 将链接 <a> 包裹在 <div> 周围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5320404/