我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。
我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。
当前回答
这对我来说很有用:
<div onclick="location.href='page.html';" style="cursor:pointer;">...</div>
其他回答
这是最简单的方法。
比如说,这是我想要的可点击的div块:
<div class="inner_headL"></div>
所以输入href,如下所示:
<a href="#">
<div class="inner_headL"></div>
</a>
只需将div块视为普通的html元素,并启用通常的a href标记。 至少在FF上是有效的。
需要一点javascript。 但是,你的div是可点击的。
<div onclick="location.href='http://www.example.com';" style="cursor:pointer;"></div>
这是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。对于没有javascript的任何人,它都可以100%优雅地降级。在我看来,用html来做这件事并不是最好的解决方案。 例如:
<div id="div_link">
<h2><a href="mylink.htm">The Link and Headline</a></h2>
<p>Some more stuff and maybe another <a href="mylink.htm">link</a>.</p>
</div>
然后使用jquery使块可点击(通过网页设计师墙):
$(document).ready(function(){
$("#div_link").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
});
然后你所要做的就是向div添加游标样式
#div_link:hover {cursor: pointer;}
为了加分,只有当javascript通过添加'js_enabled'类到div或body或其他东西来启用时才应用这些样式。
我来这里是希望能找到比我更好的解决办法,但这里提供的办法我一个都不喜欢。我想你们有些人误解了这个问题。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