HTML - 如何使整个DIV成为超链接?

Ted*_*dyk 70 html xhtml hyperlink

如何制作整个DIV可点击的超链接.意思是,我基本上想做:

<div class="myclass" href="example.com">
    <div>...</div>
    <table><tr>..</tr></table>
    ....
</div>
Run Code Online (Sandbox Code Playgroud)

每当有人将鼠标悬停在myclass上时DIV,我希望整个DIV它都是一个可点击的超链接.

Joe*_*ton 123

您可以将JavaScript的onclick添加到div中.

<div onclick="location.href='newurl.html';">&nbsp;</div>
Run Code Online (Sandbox Code Playgroud)

编辑:用于新窗口

<div onclick="window.open('newurl.html','mywindow');" style="cursor: pointer;">&nbsp;</div>
Run Code Online (Sandbox Code Playgroud)

  • 当我这样做时,我的鼠标光标不会像悬停在链接上时那样变为手形.我究竟做错了什么? (4认同)
  • 如果你修改了移动,游标:指针 - 这是有效的 (2认同)
  • 使用`cursor:pointer`而不是`cursor:hand`. (2认同)

SLa*_*aks 23

您可以在其中放置一个<a>元素<div>并将其设置为display: blockheight: 100%.

  • 这是行不通的,因为我在DIV中有很多内容.我将更新我的原始帖子,使其更具描述性 (2认同)

小智 13

您只需将光标指定为指针而不是指针,因为指针现在是标准,因此,这是示例页面代码:

<div onclick="location.href='portable-display-stands.html';" id="smallbox">The content of the div here</div>
Run Code Online (Sandbox Code Playgroud)

和示例CSS:

#smallbox {
    cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)

所以div现在是一个使用'onclick'的可点击元素,你已经用CSS伪造了手形光标......完成工作,对我有用!


Jim*_*Kye 10

这是一个迟到的答案,但这个问题在搜索结果中显得很高,因此值得正确回答.

基本上,您不应该尝试使div可点击,而是通过为<a>标记赋予display: blockCSS属性来制作类似div的锚.

这样,您的HTML在语义上保持有效,您可以继承超链接的典型浏览器行为.即使javascript被禁用/ js资源未加载,它也可以工作.


Kei*_*ler 7

添加onclick到您的DIV代码.

http://webdevjunk.com/coding/javascript/3/use-onclick-to-make-entire-div-or-other-html-object-into-a-link/

  • 另外,将div的光标样式设置为指针,这样整个东西就会得到手指. (3认同)