我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
当前回答
这招对我很管用:
HTML:
<div>
WHATEVER YOU WANT
<a href="YOUR LINK HERE">
<span class="span-link"></span>
</a>
</div>
CSS:
.span-link {
position:absolute;
width:100%;
height:100%;
top:0;
left: 0;
z-index: 9999;
}
这将添加一个不可见的元素(span),它覆盖了整个div,并且在z-index上位于整个div的上方,因此当有人点击该div时,点击基本上会被链接的不可见的“span”层拦截。
注意:如果你已经对其他元素使用了z索引,只要确保这个z索引的值高于你想让它“放在”上面的任何值。
其他回答
我自作聪明的回答是:
对“如何使块级元素成为超链接并在XHTML 1.1中验证”的回避回答
使用HTML5 DOCTYPE DTD即可。”
但ie7并不适用
onclick = " location.href =“page.html”;“
适用于IE7-9, Chrome, Safari, Firefox,
最简洁的方法是使用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。
为什么不呢?使用<a href="bla"> <div></div> </a>在HTML5中工作良好
如果你可以使用bootstrap,一个简单的解决方案是使用bootstrap .stretch -link。
https://getbootstrap.com/docs/4.3/utilities/stretched-link/
示例代码
<div class="card" style="width: 18rem;">
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card with stretched link</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-primary stretched-link">Go somewhere</a>
</div>
</div>
这个选项不需要一个空的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/所提议