我有一个<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索引的值高于你想让它“放在”上面的任何值。
其他回答
这篇文章是旧的,我知道,但我不得不解决同样的问题,因为简单地写一个普通的链接标签,显示设置为块不能使整个div在IE中可点击。所以解决这个问题要比使用JQuery简单得多。
首先让我们理解为什么会发生这种情况:IE不会使一个空的div可点击,它只使该div/a标签内的文本/图像可点击。
解决方案:用烘焙图像填充div,并隐藏它不让查看器看到。
如何? 你问得好,现在听好了。 将此背景样式添加到a标签
> "background:url('some_small_image_path')
> -2000px -2000px no-repeat;"
现在整个div都可以点击了。这对我来说是最好的方式,因为我在我的图片库中使用它,让用户点击图像的一半左右移动,然后放置一个小图像,只是为了视觉效果。所以对我来说,我使用左右图像作为背景图像!
不确定这是否有效,但它为我工作。
代码:
< 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 >
这个选项不需要一个空的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/所提议
还有一个没有提到的选项是使用flex。通过对a标记应用flex: 1,它将展开以适应容器。
div { 身高:100 px; 宽度:100 px; 显示:flex; 边框:1px实体; } 一个{ flex: 1; } < div > 链接< a href = " http://google.co.uk " > < / > < / div >
我来这里是希望能找到比我更好的解决办法,但这里提供的办法我一个都不喜欢。我想你们有些人误解了这个问题。OP希望使一个充满内容的div表现得像一个链接。其中一个例子是facebook的广告——如果你仔细观察,你会发现它们实际上是适当的标记。
对我来说,不应该的是:javascript(不应该只是一个链接,非常糟糕的SEO/可访问性);无效的HTML。
本质上是这样的:
Build your panel using normal CSS techniques and valid HTML. Somewhere in there put a link that you want to be the default link if the user clicks on the panel (you can have other links too). Inside that link, put an empty span tag (<span></span>, not <span /> - thanks @Campey) give the panel position:relative apply the following CSS to the empty span: { position:absolute; width:100%; height:100%; top:0; left: 0; z-index: 1; /* fixes overlap error in IE7/8, make sure you have an empty gif */ background-image: url('empty.gif'); } It will now cover the panel, and as it's inside an <A> tag, it's a clickable link give any other links inside the panel position:relative and a suitable z-index (>1) to bring them in front of the default span link