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

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


当前回答

这是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);
      }
    }
}

其他回答

你可以通过以下方法给你的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在IE中可点击。所以解决这个问题要比使用JQuery简单得多。

首先让我们理解为什么会发生这种情况:IE不会使一个空的div可点击,它只使该div/a标签内的文本/图像可点击。

解决方案:用烘焙图像填充div,并隐藏它不让查看器看到。

如何? 你问得好,现在听好了。 将此背景样式添加到a标签

> "background:url('some_small_image_path')
> -2000px -2000px no-repeat;"

现在整个div都可以点击了。这对我来说是最好的方式,因为我在我的图片库中使用它,让用户点击图像的一半左右移动,然后放置一个小图像,只是为了视觉效果。所以对我来说,我使用左右图像作为背景图像!

虽然我不建议在任何情况下这样做,但下面是一些代码,它将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>

如果你可以使用bootstrap,一个简单的解决方案是使用bootstrap .stretch -link。

https://getbootstrap.com/docs/4.3/utilities/stretched-link/

示例代码

<div class="card" style="width: 18rem;">
  <img src="..." class="card-img-top" alt="...">
  <div class="card-body">
    <h5 class="card-title">Card with stretched link</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
    <a href="#" class="btn btn-primary stretched-link">Go somewhere</a>
  </div>
</div>

为什么不呢?使用<a href="bla"> <div></div> </a>在HTML5中工作良好