我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
当前回答
这是实现你想要的东西的“有效”解决方案。
<style type="text/css">
.myspan {
display: block;
}
</style>
<a href="#"><span class="myspan">text</span></a>
但最可能的是,您真正想要的是将<a>标记显示为块级元素。
我不建议使用JavaScript来模拟超链接,因为这违背了标记验证的目的,标记验证的最终目的是提高可访问性(按照适当的语义规则发布格式良好的文档可以最大限度地减少不同浏览器对同一文档的不同解释)。
最好是发布一个不需要验证,但在所有浏览器(包括禁用JavaScript的浏览器)上都能正常渲染和运行的网页。此外,使用onclick不会为屏幕阅读器提供语义信息,以确定div是作为链接使用的。
其他回答
为了让同伴的答案在ie7及以后的版本中工作,它需要做一些调整。
如果元素没有背景色,IE将不支持z-index,因此链接将不会与包含内容的div的部分重叠,只与空白部分重叠。为了解决这个问题,添加了一个不透明度为0的背景。 由于某种原因,当在链接方法中使用span时,IE7和各种兼容模式完全失败。然而,如果链接本身被赋予了样式,它就可以正常工作。
.blockLink
{
position:absolute;
top:0;
left: 0;
width:100%;
height:100%;
z-index: 1;
background-color:#ffffff;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
opacity:0;
}
<div style="position:relative">
<some content>
<a href="somepage" class="blockLink" />
<div>
需要一点javascript。 但是,你的div是可点击的。
<div onclick="location.href='http://www.example.com';" style="cursor:pointer;"></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
这个选项不需要一个空的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/所提议
你不能让div本身成为一个链接,但是你可以让一个<a>标签作为一个块,与<div>具有相同的行为。
a {
display: block;
}
然后你可以设置它的宽度和高度。