我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
当前回答
你不能让div本身成为一个链接,但是你可以让一个<a>标签作为一个块,与<div>具有相同的行为。
a {
display: block;
}
然后你可以设置它的宽度和高度。
其他回答
将你的div包含在一个锚标记<a href></a>中:
<a href="">
<div>anything goes here will turn into a link</div>
</a>
这是BBC网站和《卫报》上使用的最好的表达方式:
我在这里找到了技巧: http://codepen.io/IschaGast/pen/Qjxpxo
这是HTML
<div class="highlight block-link">
<h2>I am an example header</h2>
<p><a href="pageone" class="block-link__overlay-link">This entire box</a> links somewhere, thanks to faux block links. I am some example text with a <a href="pagetwo">custom link</a> that sits within the block</p>
</div>
这里是CSS
/**
* Block Link
*
* A Faux block-level link. Used for when you need a block-level link with
* clickable areas within it as directly nesting a tags breaks things.
*/
.block-link {
position: relative;
}
.block-link a {
position: relative;
z-index: 1;
}
.block-link .block-link__overlay-link {
position: static;
&:before {
bottom: 0;
content: "";
left: 0;
overflow: hidden;
position: absolute;
right: 0;
top: 0;
white-space: nowrap;
z-index: 0;
}
&:hover,
&:focus {
&:before {
background: rgba(255,255,0, .2);
}
}
}
只是有链接在块和增强它与jquery。对于没有javascript的任何人,它都可以100%优雅地降级。在我看来,用html来做这件事并不是最好的解决方案。 例如:
<div id="div_link">
<h2><a href="mylink.htm">The Link and Headline</a></h2>
<p>Some more stuff and maybe another <a href="mylink.htm">link</a>.</p>
</div>
然后使用jquery使块可点击(通过网页设计师墙):
$(document).ready(function(){
$("#div_link").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
});
然后你所要做的就是向div添加游标样式
#div_link:hover {cursor: pointer;}
为了加分,只有当javascript通过添加'js_enabled'类到div或body或其他东西来启用时才应用这些样式。
不确定这是否有效,但它为我工作。
代码:
< div风格= '位置:相对;background - color: # 000000;宽度:600 px;高度:30 px;边界:固体;“> <p style='display:inline;color:#ffffff;float:left; <a style='position:absolute;top:0px;left:0px;width:100%;height:100%;display:inline;' href ='#'></a> . < / div >
为什么不呢?使用<a href="bla"> <div></div> </a>在HTML5中工作良好