我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
当前回答
您还可以尝试包装一个锚,然后将其高度和宽度与其父相同。这对我来说非常合适。
<div id="css_ID">
<a href="http://www.your_link.com" style="display:block; height:100%; width:100%;"></a>
</div>
其他回答
将你的div包含在一个锚标记<a href></a>中:
<a href="">
<div>anything goes here will turn into a link</div>
</a>
这是一个古老的问题,但我想我应该回答它,因为这里的每个人都有一些疯狂的解决方案。其实非常非常简单……
锚标记是这样工作的-
<a href="whatever you want"> EVERYTHING IN HERE TURNS INTO A LINK </a>
Sooo ...
<a href="whatever you want"> <div id="thediv" /> </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和HTML中引入的数据标记。使用这个解决方案,您可以在每个标签上创建一个链接。首先用data-link标签定义标签(例如div):
<div data-link="http://www.google.at/">Some content in the div which is arbitrary</div>
现在,您可以随意设置div的样式。你还必须为类似“link”的行为创建样式:
[data-link] {
cursor: pointer;
}
最后把jQuery调用放到页面上:
$(document).ready(function() {
$("[data-link]").click(function() {
window.location.href = $(this).attr("data-link");
return false;
});
});
jQuery通过这段代码对页面上具有“data-link”属性的每个标记应用一个点击监听器,并重定向到数据链接属性中的URL。
这个选项不需要一个空的gif,就像被点赞最多的答案一样:
HTML:
<div class="feature">
<a href="http://www.example.com"></a>
</div>
CSS:
div.feature {
position: relative;
}
div.feature a {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
text-decoration: none; /* No underlines on the link */
z-index: 10; /* Places the link above everything else in the div */
background-color: #FFF; /* Fix to make div clickable in IE */
opacity: 0; /* Fix to make div clickable in IE */
filter: alpha(opacity=1); /* Fix to make div clickable in IE */
}
如http://www.digitalskydesign.com/how-to-make-an-entire-div-a-link-using-css/所提议