可以像这样<a>
在<div>
s 周围包装标签:
<a href=etc etc>
<div class="layout">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
</div>
</a>
Run Code Online (Sandbox Code Playgroud)
Eclipse告诉我div是在错误的地方?如果不允许这样做.如何让整个"布局"类成为链接?
Yi *_*ang 76
该结构在HTML5中有效,因为在HTML5锚点中几乎可以包装除了其他锚点和表单控件之外的任何元素.现在大多数浏览器都支持此功能,并将问题中的代码解析为有效的HTML.以下答案写于2011年,如果您支持旧浏览器(*cough*Internet Explorer*cough*),可能会有用.
没有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>
Run Code Online (Sandbox Code Playgroud)
然后风格 display: block
使用JavaScript和:hover
:
<div class="layout">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
并且(假设jQuery)
$('.layout').click(function(){
// Do something
}):
Run Code Online (Sandbox Code Playgroud)
和
.layout:hover {
// Hover effect
}
Run Code Online (Sandbox Code Playgroud)
或者最后使用绝对定位来放置a
带有CSS 的锚来覆盖整个.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>
Run Code Online (Sandbox Code Playgroud)
和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;
}
Run Code Online (Sandbox Code Playgroud)
当然,这不适用于旧版本的IE.
小智 14
虽然<a>
不允许标记包含<div>
元素,但允许包含其他内联元素,例如<span>
.
当我遇到问题时,我用div交换了div标签<span>
.由于span标记是内联元素,因此您需要将a display:block
应用于<span>
元素的css,以使其行为类似于<div>
块元素.这应该是有效的xhtml,不需要任何JavaScript.
这是一个例子:
<a href="#">
<span style="display:block">
Some content. Maybe some other span elements, or images.
</span>
</a>
Run Code Online (Sandbox Code Playgroud)
小智 8
另一个简单的解决方案-只需向div中添加一个onclick事件处理程序即可:
<div class="layout" onclick="location.href='somewhere'">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这对我来说很棒,但是有一个小陷阱。我不确定这对搜索引擎的友好程度。我担心Google的网络抓取工具可能找不到此链接,因此我也倾向于在块中的某个地方包括传统的A HREF链接,如下所示:
<div class="layout" onclick="location.href='destination_url'">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
<a href="destination_url">This is a link</a>
</div>
Run Code Online (Sandbox Code Playgroud)
Timothy的解决方案是正确的......而不是在div周围包裹一个锚...你只需使用display:block给锚元素布局并添加锚的大小和宽度......
.div_class { width: 100px; height: 100px; }
.div_class a { width: 100px; height: 100px; display: block; }
<div class='div_class'><a href="#"></a></div>
Run Code Online (Sandbox Code Playgroud)
您只想将“a”标签设置为display: block;
Eclipse 适当地告诉您您的 HTML 不符合规范(因为锚标记中不允许使用 div 标记)。
但是,由于您似乎希望在视觉上使锚看起来像一个大盒子,因此只需将其设计为这样:)