我有一个<div>块与一些花哨的视觉内容,我不想改变。我想让它成为一个可点击的链接。

我正在寻找类似于<a href="…"><div>…</div></a>,但这是有效的XHTML 1.1。


当前回答

你可以通过以下方法给你的div一个链接:

<div class="boxdiv" onClick="window.location.href='https://www.google.co.in/'">google</div>
<style type="text/css">
.boxdiv {
    cursor:pointer;
    width:200px;
    height:200px;
    background-color:#FF0000;
    color:#fff;
    text-align:center;
    font:13px/17px Arial, Helvetica, sans-serif;
    }
</style>

其他回答

您还可以尝试包装一个锚,然后将其高度和宽度与其父相同。这对我来说非常合适。

<div id="css_ID">
    <a href="http://www.your_link.com" style="display:block; height:100%; width:100%;"></a>
</div>

你不能让div本身成为一个链接,但是你可以让一个<a>标签作为一个块,与<div>具有相同的行为。

a {
    display: block;
}

然后你可以设置它的宽度和高度。

这个选项不需要一个空的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/所提议

<a href="…" style="cursor: pointer;"><div> … </div></a>

实际上你现在需要包括JavaScript代码, 请查看本教程。

但有一个棘手的方法来实现这个使用CSS代码 你必须在你的div标签内嵌套一个锚标签,你必须应用这个属性,

display:block;

当你这样做了,它将使整个宽度区域可点击(但在锚标签的高度内),如果你想覆盖整个div区域,你必须将锚标签的高度设置为div标签的高度,例如:

height:60px;

这将使整个区域可点击,然后你可以应用text-indent:-9999px到锚标签来实现目标。

这是非常棘手和简单的,它只是用CSS代码创建的。

这里有一个例子:http://jsfiddle.net/hbirjand/RG8wW/