简体   繁体   English

使 div 成为可点击的链接

[英]Making div a clickable link

I have a PHP search script that parses results into HTML div elements to make styling the results easier.我有一个 PHP 搜索脚本,它将结果解析为 HTML div 元素,以使结果的样式更容易。 I have the following code:我有以下代码:

<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='url'>{$row['url']}</div><div class='desc'>{$row['description']}</div></div>

I want to make it so when a the whole webresult div is clicked on, it goes to the url of the result.我想这样做,当单击整个 webresult div 时,它会转到结果的 url。

I hope people can understand what I'm trying to describe.我希望人们能理解我试图描述的内容。

If you want to make the entire div clickable, try to style the <a> element as a block element and make its size equivalent to the parent <div> , ie,如果要使整个 div 可点击,请尝试将<a>元素设置为块元素,并使其大小等于父<div> ,即

.title a {
  display: block;
  width: 100%;
  height: 100%;
}

use jQuery:使用 jQuery:

$('.webresult').click(function() {
   window.location.href = $(this).find('a').attr('href');
});

Best to do this via javascript.最好通过 javascript 执行此操作。 If using jQuery, you could do this:如果使用 jQuery,您可以这样做:

$('.webresult').click(function(){
    $('this').find('a').click();
})

Wrap the anchor around everything instead of just the row title, and set it to display: block;将锚点包裹在所有内容上,而不仅仅是行标题,并将其设置为display: block; in css.在 css 中。 Further style the anchor the way you previously styled the div, and drop the div altogether.以您之前设置 div 的方式进一步设置锚点的样式,并完全删除 div。 You probably also want to set the text color (including for:hover) and remove the underline using the text-decoration property.您可能还想设置文本颜色(包括 for:hover)并使用 text-decoration 属性删除下划线。

If you decide to go with one of the javascript options the others posted, make sure you have a graceful fallback.如果您决定 go 使用其他人发布的 javascript 选项之一,请确保您有一个优雅的后备。 Not everyone has javascript enabled.不是每个人都启用了 javascript。

I would do this with jQuery:我会用 jQuery 做到这一点:

$(".webresult").click(function() {
    window.location.href = $(this).find("a").attr("href");
});

Another solution is that within the HTML 5 spec, block elements can actually be links to other places.另一个解决方案是在 HTML 5 规范中,块元素实际上可以链接到其他地方。 You can read more about that here: http://html5doctor.com/block-level-links-in-html-5/您可以在此处阅读更多相关信息: http://html5doctor.com/block-level-links-in-html-5/

isn't不是

<div onclick="location.href='/the_url/'">

what you need?你需要什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM