我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
当前回答
虽然我不建议在任何情况下这样做,但下面是一些代码,它将DIV转换为链接(注意:本例使用jQuery,为了简单起见,删除了某些标记):
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("div[href]").click(function () {
window.location = $(this).attr("href");
});
});
</script>
<div href="http://www.google.com">
My Div Link
</div>
其他回答
<a href="…" style="cursor: pointer;"><div> … </div></a>
您还可以尝试包装一个锚,然后将其高度和宽度与其父相同。这对我来说非常合适。
<div id="css_ID">
<a href="http://www.your_link.com" style="display:block; height:100%; width:100%;"></a>
</div>
这是最简单的方法。
比如说,这是我想要的可点击的div块:
<div class="inner_headL"></div>
所以输入href,如下所示:
<a href="#">
<div class="inner_headL"></div>
</a>
只需将div块视为普通的html元素,并启用通常的a href标记。 至少在FF上是有效的。
我来这里是希望能找到比我更好的解决办法,但这里提供的办法我一个都不喜欢。我想你们有些人误解了这个问题。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
这个例子很适合我:
<div style="position: relative; width:191px; height:83px;">
<a href="link.php" style="display:block; width:100%; height:100%;"></a>
</div>