Html 怎么把div标签变成链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1685078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you make a div tag into a link
提问by Alan
How do you make a div tag into a link. I would like my entire div to be clickable.
你如何将一个 div 标签变成一个链接。我希望我的整个 div 都可以点击。
回答by eozzy
JS:
JS:
<div onclick="location.href='url'">content</div>
jQuery:
jQuery:
$("div").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
Make sure to use cursor:pointer
for these DIVs
确保cursor:pointer
用于这些 DIV
回答by Justin Yost
If you have to set your anchor tag inside the div, you can also use CSS to set the anchor to fill the div via display:block.
如果必须在 div 内设置锚标记,也可以使用 CSS 设置锚以通过 display:block 填充 div。
As such:
像这样:
<div style="height: 80px"><a href="#" style="display: block">Text</a></div>
Now when the user floats their cursor in that div the anchor tag will fill the div.
现在,当用户将光标悬停在该 div 中时,锚标记将填充该 div。
回答by Rael Gugelmin Cunha
If you're using HTML5, as pointed in this otherquestion, you can put your div
inside a
:
如果您使用的是 HTML5,如另一个问题中所指出的,您可以将您的div
inside a
:
<a href="http://www.google.com"><div>Some content here</div></a>
Preffer this method as it makes clear in your structure that all the content is clickable, and where it's pointing.
首选此方法,因为它在您的结构中清楚地表明所有内容都是可点击的,以及它指向的位置。
回答by zzzzBov
So you want an element to be something it's not?
所以你想让一个元素成为它不是的东西?
Generally speaking this isn't a good idea. If you need a link, use a link. Most of the time it's easier to just use the appropriate markup where it belongs.
一般来说,这不是一个好主意。如果您需要链接,请使用链接。大多数情况下,在它所属的地方使用适当的标记会更容易。
That all said, sometimes you just have to break the rules. Now, the question doesn't have javascript, so I'm going to put the disclaimer here:
话虽如此,有时你只需要打破规则。现在,这个问题没有javascript,所以我要在这里放免责声明:
You can't have a <div>
act as a link without either using a link (or equivalent, such as a <form>
that only contains a submit button) or using JavaScript.
如果不<div>
使用链接(或等效的,例如<form>
只包含提交按钮的 )或使用 JavaScript,您就不能将行为作为链接。
From here on out, this answer is going to assume that JavaScript is allowed, and furthermore that jQuery is being used (for brevity of example).
从现在开始,这个答案将假设 JavaScript 是允许的,而且正在使用 jQuery(为了简单起见)。
With that all said, lets dig into what makes a link a link.
说了这么多,让我们深入研究是什么使链接成为链接。
Links are generally elements that you click on so that they navigate you to a new document.
链接通常是您单击的元素,以便它们将您导航到新文档。
It seems simple enough. Listen for a click event and change the location:
这似乎很简单。侦听单击事件并更改位置:
Don't do this不要这样做$('.link').on('click', function () {
window.location = 'http://example.com';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link">Fake Link</div>
There you have it, the <div>
is now a link. Wait...what's that? What about accessibility? Oh right, screen readers and users of assistive technology won't be able to click on the link, especially if they're only using the keyboard.
你有它,<div>
现在是一个链接。等等……那是什么?可访问性怎么样?哦对了,屏幕阅读器和辅助技术用户将无法点击链接,尤其是当他们只使用键盘时。
Fixing that's pretty simple, let's allow keyboard only users to focus the <div>
, and trigger the click event when they press Enter:
解决这个问题非常简单,让我们只允许键盘用户聚焦<div>
,并在他们按下时触发点击事件Enter:
$('.link').on({
'click': function () {
window.location = 'http://example.com';
},
'keydown': function (e) {
if (e.which === 13) {
$(this).trigger('click');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link" tabindex="0">Fake Link</div>
Again, there you have it, this <div>
is now a link. Wait...again? Still accessibility problems? Oh ok, so it turns out that the assistive technology doesn't know that the <div>
is a link yet, so even though you can get there via keyboard, users aren't being told what to do with it.
再次,你有它,这<div>
是一个链接。等等……又来了?仍然存在可访问性问题?哦,好吧,原来辅助技术还不知道这<div>
是一个链接,所以即使你可以通过键盘到达那里,用户也不会被告知如何处理它。
Fortunately, there's an attribute that can be used to override an HTML element's default role, so that screen readers and the like know how to categorize customized elements, like our <div>
here. The attribute is of course the [role]
attribute, and it nicely tells screen readers that our <div>
is a link:
幸运的是,有一个属性可用于覆盖 HTML 元素的默认角色,以便屏幕阅读器等了解如何对自定义元素进行分类,例如我们的<div>
here。属性当然是[role]
属性,它很好地告诉屏幕阅读器我们<div>
是一个链接:
$('[role="link"]').on({
'click': function () {
window.location = 'http://example.com';
},
'keydown': function (e) {
if (e.which === 13) {
$(this).trigger('click');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="link" tabindex="0">Fake Link</div>
Finally, our <div>
is a lin---oh now the other devs are complaining. What now?
最后,我们<div>
是 lin --- 哦,现在其他开发人员都在抱怨。现在怎么办?
Ok, so the devs don't like the code. They tried to preventDefault
on the event, and it just keeps working. That's easy to fix:
好的,所以开发人员不喜欢代码。他们试图参加preventDefault
这个活动,但它一直在工作。这很容易解决:
$(document).on({
'click': function (e) {
if (!e.isDefaultPrevented()) {
window.location = 'http://example.com';
}
},
'keydown': function (e) {
if (e.which === 13 && !e.isDefaultPrevented()) {
$(this).trigger('click');
}
}
}, '[role="link"]');
$('[aria-disabled="true"]').on('click', function (e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="link" tabindex="0">Fake Link</div>
<div role="link" aria-disabled="true" tabindex="0">Fake disabled link</div>
There we have it---THERE'S MORE? What else don't I know? Tell me everything NOWso that I can fix it!
我们有它——还有更多?还有什么我不知道的?告诉我一切现在这样我就可以修复它!
- Ok, so there's no way to specify target. We can fix that by updating to
window.open
. - Click events and keyboard events are ignoring Ctrl, Alt, and Shiftkeys. That's easy enough, just need to check those values on the event object.
- There's no way to specify contextual data. Let's just add some
[data-*]
attributes, and call it a day with that one. - The click event isn't obeying the mouse button that's being used, middle mouse should open in a new tab, right mouse shouldn't be triggering the event. Easy enough, just add some more checks to the event listeners.
- The styles look weird. WELL OF COURSE THE STYLES ARE WEIRD, IT'S A
<DIV>
NOT AN ANCHOR!
- 好的,所以没有办法指定目标。我们可以通过更新到
window.open
. - 点击事件和键盘事件忽略Ctrl,Alt和Shift钥匙。这很简单,只需要检查事件对象上的这些值。
- 无法指定上下文数据。让我们只添加一些
[data-*]
属性,然后就用它来结束吧。 - 单击事件不服从正在使用的鼠标按钮,鼠标中键应在新选项卡中打开,鼠标右键不应触发该事件。很简单,只需向事件侦听器添加更多检查即可。
- 样式看起来很奇怪。当然,风格很奇怪,它
<DIV>
不是锚!
well, I'll address the first four issues, and NO MORE. I've had it with this stupid custom element garbage. I should have just used an <a>
element from the beginning.
好吧,我将解决前四个问题,不再赘述。我已经有了这个愚蠢的自定义元素垃圾。我应该<a>
从一开始就使用一个元素。
$(document).on({
'click': function (e) {
var target,
href;
if (!e.isDefaultPrevented() && (e.which === 1 || e.which === 2)) {
target = $(this).data('target') || '_self';
href = $(this).data('href');
if (e.ctrlKey || e.shiftKey || e.which === 2) {
target = '_blank'; //close enough
}
open(href, target);
}
},
'keydown': function (e) {
if (e.which === 13 && !e.isDefaultPrevented()) {
$(this).trigger({
type: 'click',
ctrlKey: e.ctrlKey,
altKey: e.altKey,
shiftKey: e.shiftKey
});
}
}
}, '[role="link"]');
$('[aria-disabled="true"]').on('click', function (e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="link" tabindex="0" data-href="http://example.com/">Fake Link</div>
<div role="link" tabindex="0" data-href="http://example.com/" data-target="_blank">Fake Link With Target</div>
<div role="link" aria-disabled="true" tabindex="0" data-href="http://example.com/">Fake disabled link</div>
Note that stack snippets won't open popup windows because of how they're sandboxed.
请注意,堆栈片段不会打开弹出窗口,因为它们是如何被沙盒化的。
That's it. That's the end of this rabbit hole. All of that craziness when you could have simply had:
就是这样。这就是这个兔子洞的尽头。当您本可以简单地拥有所有这些疯狂时:
<a href="http://example.com/">
...your markup here...
</a>
The code I posted here probably has problems. It probably has bugs that even I don't realize as of yet. Trying to duplicate what browsers give you for free is tough. There are so many nuances that are easy to overlook that it's simply not worth trying to emulate it 99% of the time.
我在这里发布的代码可能有问题。它可能有一些错误,甚至我还没有意识到。试图复制浏览器免费提供给你的东西是很困难的。有很多细微差别很容易被忽视,以至于在 99% 的情况下都不值得尝试模仿它。
回答by chakrit
DON'T DO IT.
不要这样做。
- If you want a link, wrap the content in the proper
<A>NCHOR</a>
. - If you want to turn the
<DIV>
into a link, use "Javascript" to wrap the<DIV>
inside an<A>NCHOR</A>
- If you want to perform some action when clicking the
<DIV>
use theonclick
event handler... and don't call it a "link".
- 如果需要链接,请将内容包装在正确的
<A>NCHOR</a>
. - 如果你想把它
<DIV>
变成一个链接,用“Javascript”把<DIV>
里面包裹起来<A>NCHOR</A>
- 如果您想在单击时执行某些操作,请
<DIV>
使用onclick
事件处理程序...并且不要将其称为“链接”。
回答by Ryan Michela
<div style="cursor:pointer" onclick="document.location='http://www.google.com'">Content Goes Here</div>
回答by plainprogrammer
You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:
您可以使用 Javascript 来实现此效果。如果你使用一个框架,这种事情就变得很简单了。这是jQuery 中的一个示例:
$('div#id').click(function (e) {
// Do whatever you want
});
This solution has the distinct advantage of keeping the logic not in your markup.
此解决方案具有将逻辑保留在标记中的独特优势。
回答by Ben Regenspan
You can make the entire DIV function as a link by adding an onclick="window.location='TARGET URL'" and by setting its style to "cursor:pointer". But it's often a bad idea to do this because search engines won't be able to follow the resulting link, readers won't be able to open in tabs or copy the link location, etc. Instead, you can create a regular anchor tag and then set its style to display:block , and then style this as you would a DIV.
您可以通过添加 onclick="window.location='TARGET URL'" 并将其样式设置为 "cursor:pointer" 来使整个 DIV 函数成为一个链接。但是这样做通常是一个坏主意,因为搜索引擎将无法跟踪生成的链接,读者将无法在选项卡中打开或复制链接位置等。相反,您可以创建一个常规的锚标记然后将其样式设置为 display:block ,然后将其设置为 DIV 样式。
回答by Rob
<div style="cursor:pointer;" onclick="document.location='http://www.google.com'">Foo</div>
回答by sifr4
Keep in mind that search spiders don't index JS code. So, if you put your URL
inside JS code and make sure to also include it inside a traditional HTML link elsewhere on the page.
请记住,搜索蜘蛛不会索引 JS 代码。因此,如果您将URL
内部 JS 代码放入并确保将其包含在页面其他位置的传统 HTML 链接中。
That is, if you want the linked pages to be indexed by Google, etc.
也就是说,如果您希望链接的页面被 Google 等编入索引。