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

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


当前回答

这是实现你想要的东西的“有效”解决方案。

<style type="text/css">
.myspan {
    display: block;
}
</style>
<a href="#"><span class="myspan">text</span></a>

但最可能的是,您真正想要的是将<a>标记显示为块级元素。

我不建议使用JavaScript来模拟超链接,因为这违背了标记验证的目的,标记验证的最终目的是提高可访问性(按照适当的语义规则发布格式良好的文档可以最大限度地减少不同浏览器对同一文档的不同解释)。

最好是发布一个不需要验证,但在所有浏览器(包括禁用JavaScript的浏览器)上都能正常渲染和运行的网页。此外,使用onclick不会为屏幕阅读器提供语义信息,以确定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>

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

我引入了一个变量,因为我的链接中的一些值将根据用户来自的记录而改变。 这适用于测试:

   <div onclick="location.href='page.html';"  style="cursor:pointer;">...</div> 

这个也有用:

   <div onclick="location.href='<%=Webpage%>';"  style="cursor:pointer;">...</div> 

你可以使用href标签环绕元素,或者你可以使用jquery和使用

$('').click(function(e){
e.preventDefault();
//DO SOMETHING
});

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

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