简体   繁体   English

div是否有可能像HTML锚标签一样工作?

[英]Is it possible for a `div` to act like an HTML anchor tag?

I'd like a way to have a block-level HTML tag act like an <a> tag. 我想要一种使块级HTML标记像<a>标记一样起作用的方法。

I've been using React and React-Router for a while now and tend to use <div> for a lot of components. 我已经使用React和React-Router一段时间了,并且倾向于将<div>用于很多组件。 Because I wrapping an anchor tag in a block-level tag such as <div> isn't valid HTML, I can't add browser-known links in my apps. 因为我将锚定标记包装在块级标记(例如<div> )中不是有效的HTML,所以无法在应用程序中添加浏览器已知的链接。

One idea I had is to write all my components as a <span> . 我的一个想法是将所有组件都写为<span> Sadly, this isn't the solution I want since I also don't control the HTML 3rd party components. 可悲的是,这不是我想要的解决方案,因为我也不控制HTML 3rd party组件。

How would I make it so a div or any other block-level tag, act like an anchor tag where hovering shows a link in the bottom of the browser, [CTRL][LEFT_CLICK] and [MIDDLE_CLICK] open a new tab, and a single click changes the route? 我将如何使其成为div或任何其他块级标记,就像锚标记一样,其中悬停在浏览器底部显示一个链接,[CTRL] [LEFT_CLICK]和[MIDDLE_CLICK]打开一个新标签,单击更改路线?

A React solution isn't required. 不需要React解决方案。

I would suggest two ways of doing it 我会建议两种方法

Use little JavaScript 使用少量JavaScript

<div onclick="location.href='http://www.thelink.com';" style="cursor:pointer;"></div>

Make <a> act like a div 使<a>得像div

a {
    display: block;
}

You can set other stuff say height and width. 您可以设置其他内容,例如高度和宽度。

Hope this helps. 希望这可以帮助。

You should be using <a> instead of <div> if those requirements are necessary. 如果需要这些要求,则应使用<a>而不是<div>

While this wasn't the case in the past, HTML5 allows you to wrap anchor tags around block-level elements: https://stackoverflow.com/a/1828032/1624862 虽然过去不是这种情况,但是HTML5允许您将锚点标签包装在块级元素周围: https : //stackoverflow.com/a/1828032/1624862

There are still limitations though. 虽然仍然有限制。 If you wrap your <a> in a <span> , then you have to have inline elements inside. 如果将<a>包装在<span> ,则必须在其中包含内联元素。 Block-level elements are only allowed inside <a> when it's also wrapped in a block-level element. 仅当<a>也包含块级元素时,才允许使用块级元素。

You can't wrap anchor tag around div but can do vice versa won't that help. 您不能在div周围包裹锚标记,但反之亦然也无济于事。

Link 链接

Please take a look at below code sandbox link. 请查看下面的代码沙箱链接。 https://codesandbox.io/s/9z5y52mk8w https://codesandbox.io/s/9z5y52mk8w

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

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