HTML - 如何使整个 DIV 成为超链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2188272/
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
HTML - how to make an entire DIV a hyperlink?
提问by Teddyk
How do I make an entire DIV
a clickable hyperlink. Meaning, I essentially want to do:
如何使整个DIV
链接成为可点击的超链接。意思是,我基本上想做:
<div class="myclass" href="example.com">
<div>...</div>
<table><tr>..</tr></table>
....
</div>
And whenever someone mouse hovers of the myclass DIV
, I want the entire DIV
it to be a clickable hyperlink.
每当有人鼠标悬停在 myclass 上时DIV
,我都希望DIV
它是一个可点击的超链接。
回答by Joel Etherton
You can add the onclick for JavaScript into the div.
您可以将 JavaScript 的 onclick 添加到 div 中。
<div onclick="location.href='newurl.html';"> </div>
EDIT: for new window
编辑:对于新窗口
<div onclick="window.open('newurl.html','mywindow');" style="cursor: pointer;"> </div>
回答by SLaks
You can put an <a>
element inside the <div>
and set it to display: block
and height: 100%
.
您可以将一个<a>
元素放入<div>
并将其设置为display: block
and height: 100%
。
回答by Nick Annies
You just need to specify the cursor as a pointer, not a hand, as pointer is now the standard, so, here's the example page code:
您只需要将光标指定为指针,而不是手,因为指针现在是标准的,因此,这是示例页面代码:
<div onclick="location.href='portable-display-stands.html';" id="smallbox">The content of the div here</div>
and the example CSS:
和示例 CSS:
#smallbox {
cursor: pointer;
}
So the div is now a clickable element using 'onclick' and you've faked the hand cursor with the CSS...job done, works for me!
所以 div 现在是一个使用 'onclick' 的可点击元素,你已经用 CSS 伪造了手形光标......工作完成,对我有用!
回答by Jimmy Breck-McKye
This is a late answer, but this question appears highly on search results so it's worth answering properly.
这是一个迟到的答案,但这个问题在搜索结果中出现的频率很高,因此值得正确回答。
Basically, you shouldn't be trying to make a div clickable, but rather make an anchor div-like by giving the <a>
tag a display: block
CSS attribute.
基本上,您不应该尝试使 div 可点击,而应该通过为<a>
标签提供display: block
CSS 属性来使锚点 div 类似。
That way, your HTML remains semantically valid and you can inherit the typical browser behaviours for hyperlinks. It also works even if javascript is disabled / js resources don't load.
这样,您的 HTML 将在语义上保持有效,并且您可以继承超链接的典型浏览器行为。即使 javascript 被禁用/js 资源没有加载,它也能工作。
回答by Keith Adler
回答by cfg
Why don't you just do this
你为什么不这样做
<a href="yoururl.html"><div>...</div></a>
That should work fine and will prompt the "clickable item" cursor change, which the aforementioned solution will not do.
这应该可以正常工作,并会提示“可点击项目”光标更改,而上述解决方案不会这样做。
回答by tDo
alternative would be javascript and forwarding via the onclick event
替代方法是 javascript 并通过 onclick 事件转发
<div onclick="window.location.href='somewhere...';">...</div>