gpt4 book ai didi

javascript - HTML 语义 - 充当 anchor 的按钮

转载 作者:行者123 更新时间:2023-12-03 07:16:58 26 4
gpt4 key购买 nike

我主要对 感兴趣 a11y 方面
因此,您可能知道,有时您可能希望有一个用作 anchor 的按钮。
这些是解决这个问题的 4 种方法(我能想到):
1. anchor 元素内的按钮

<a href="//redirection"><button>Button</button></a>
2. 在按钮元素内锚定
<button><a href="//redirection">Button</a></button>
<!-- Also should it be a href or button onclick (?) -->
3. Anchor 样式为按钮(没有按钮元素)
<a class="buttonLike" href="//redirection">Button</a>
4. 用作重定向的按钮(没有 anchor 元素):
const button = document.getElementById('button')
button.addEventListener('click', () => {
window.location.href = "//redirection"
})

<button id="button">Button</button>

我试图自己找到这个问题的答案。我能找到的最接近的是这段摘录:
根据 MDN anchor spec ,其中规定了以下内容:

Anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events .

These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.

Use a <button> instead. In general, you should only use a hyperlink for navigation to a real URL.


不幸的是,这对我没有太大帮助。基本上它所声明的是,如果您不想提供真正的链接,则不应使用第三种方法(锚定为按钮),这不是这个问题的意义所在。
有没有官方 WCAG关于这个我无法找到的主题?

最佳答案

选项 1 不是有效的 HTML。
选项 2 不是有效的 HTML。
选项 3 是这里的正确选择。
选项 4 在语义上是 不正确。
语义是可访问性最重要的方面之一。
有两件事决定了选项 3。
第一个是 anchor 应该只用于跳转到部分和在页面之间导航。
第二个是按钮应该执行操作在同一页上 .
现在,如果您想将号召性用语链接设置为看起来像一个很好的按钮,但请确保使用正确的语义,但请确保 CTA 指向新页面 或者它在语义上不正确。
虽然它在 StackOverflow 上发誓要提到 SEO,但超链接而不是 JavaScript 重定向会好得多。

关于javascript - HTML 语义 - 充当 anchor 的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64443645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com