<a>
代表锚
如果您包括[href]
上的属性<a>
元素,它是一个指向某个位置的锚点,这意味着您可以转到一个新页面,即当前页面的特定片段(因此#
称为片段标识符),或新页面的特定片段。
<a>
没有的元素[href]
属性在历史上被指定为[name]
属性,可以用作片段标识符的目的地。浏览器后来添加了对链接到任何项目的支持[id]
属性,现在这是链接到文档片段的首选方法。
这对于独立版意味着什么<a>
元素?
An a[href]
元素是一个link(这就是为什么它们与:link
在 CSS 中)。links是可点击的。An a元素没有[href]否则,属性只是一个占位符,用于放置链接的位置 https://www.w3.org/TR/html5/single-page.html#the-a-element,并且不可点击,也不在页面的选项卡顺序中。
如果您希望链接可通过键盘导航,这对于可访问性很重要(WAI-ARIA http://www.w3.org/WAI/intro/aria.php),您需要执行以下操作之一:
- 将元素更改为
<button type="button">
- 保持
[href]
属性
- add
[tabindex="0"]
和其中之一[role="button"]
or [role="link"]
(可能还有一些样式)
有关的更多信息[role]
属性可以在中找到角色模型部分 http://www.w3.org/TR/wai-aria/roles of the WAI-ARIA 文档 http://www.w3.org/TR/wai-aria/.
更改标记
如果您没有理由保留[href]
属性,您不妨使用<button>
元素:
<button type="button">
^^^^^^^^^^^^^
The [type]
属性用于使元素成为通用按钮,否则<button>
将默认为[type="submit"]
,这可能是不可取的,因为它可能会触发表单提交。
如果您不能使用<button>
(通常发生在内部标记必须包含<div>
)你可以伪造一个<button>
using:
<div role="button" tabindex="0">Some clickable text</div>
You'll need to listen for keypress
events and trigger click
events for Enter and Space.
保留标记
如果您保留<a>
元素及其[href]
属性,其值有多种选项。
真实的链接
E.x.
<a href="/some/location/for/users/without/js">
<a href="#document-fragment">
如果您需要为禁用 JS 的用户提供支持,您不妨将他们引导到一个无需 JS 即可执行等效功能的页面。
通过扩展,这还包括提供文档片段链接以链接到同一文档中的内容。例如,可切换区域可以标记为:
<a href="#more" class="toggleable">Read More</a>
<div id="more">Lorem ipsum dolor sit amet</div>
因此,使用 JS,该区域可以折叠和展开,而如果没有 JS,链接会将用户带到页面上的相应内容。
一个无用的href
E.x.
<a href="#">
<a href="javascript:void(0)">
<a href="about:blank">
If you're preventing the default behavior behind-the-scenes in JavaScript, and you're not supporting users with JS disabled, you can use a "dud" href value to keep the link in the tabbing order and automatically enable Enter to trigger the click
event. You should add [role="button"]
as semantically the <a>
tag is no longer being used as a link, but as a button.
<a href="#" role="button">Some clickable text</a>