如何使用CSS单击整个div [英] How to make an entire div clickable with CSS

查看:175
本文介绍了如何使用CSS单击整个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时您想将整个div(或其他元素)变为可点击的链接。这是一个例子。

Sometimes you want to make an entire div (or other element) into a clickable link. Here’s an example.

这是使用纯CSS的跨浏览器方式:

Here’s a cross-browser way to do it using pure CSS:

HTML:

<div class="clickable">
    <a href="URL_OF_LINK_TARGET"> </a>
    Rest of div content goes here
</div>
CSS:

div.clickable { /* Containing div must have a position value */
    position:relative;
}
div.clickable a {
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    left:0;
    text-decoration:none; /* Makes sure the link   doesn't get underlined */
    z-index:10; /* raises anchor tag above everything else in div */
    background-color:white; /*workaround to make clickable in IE */
    opacity: 0; /*workaround to make clickable in IE */
    filter: alpha(opacity=1); /*workaround to make clickable in IE */
}

首先,位置。这样,当我们将position:absolute;应用到链接(见下一段)时,它将相对于包含的div定位。

First, give the containing div position. That way, when we apply "position:absolute;" to the link (see next paragraph) it will position itself relative to the containing div.

绝对定位和包含div的完整大小和深度。链接的z-index确保它在div的所有其他位置,所以无论你在哪里点击,你都点击链接。

Next, make the link absolutely positioned and the full size and depth of the containing div. The link’s z-index makes sure it’s above everything else in the div, so no matter where you click, you’re clicking the link.

IE,自然,有怪癖。在这种情况下,IE需要这样的链接的背景颜色是可点击的,所以我们给它一个背景颜色(白色),设置不透明度为0,然后给它一个IE的唯一不透明度为1%使用IE的专有过滤属性。

IE, naturally, has quirks. In this case, IE requires a background color for such a link to be clickable, so we give it a background color (white), set the opacity to 0, then give it an IE-only opacity of 1% using IE’s proprietary filter property.

最后,在div中放入你想要的任何内容。如果你要使用z-index对内容进行分层,只要确保不要给任何元素比链接更高的z-index。

Finally, put whatever content you want in the div. If you’re going to be layering the content using z-index, just make sure not to give any element a higher z-index than the link.

推荐答案

您可以在一个链接中封装一个div,它是有效的HTML5。

You can wrap a div in a link and it is valid HTML5.

<a href="#">
      <div></div>
</a>

这篇关于如何使用CSS单击整个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆