如何创建一个像链接一样的 HTML 按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2906582/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:10:48  来源:igfitidea点击:

How to create an HTML button that acts like a link?

htmlbuttonhyperlinkanchorhtmlbutton

提问by Andrew

I would like to create an HTML button that acts like a link. So, when you click the button, it redirects to a page. I would like it to be as accessible as possible.

我想创建一个像链接一样的 HTML 按钮。因此,当您单击该按钮时,它会重定向到一个页面。我希望它尽可能易于访问。

I would also like it so there aren't any extra characters, or parameters in the URL.

我也很喜欢它,所以 URL 中没有任何额外的字符或参数。

How can I achieve this?

我怎样才能做到这一点?



Based on the answers posted so far, I am currently doing this:

根据到目前为止发布的答案,我目前正在这样做:

<form method="get" action="/page2">
    <button type="submit">Continue</button>
</form>

but the problem with this is that in Safariand Internet Explorer, it adds a question mark character to the end of the URL. I need to find a solution that doesn't add any characters to the end of the URL.

但问题在于,在SafariInternet Explorer 中,它会在 URL 末尾添加一个问号字符。我需要找到一个不会在 URL 末尾添加任何字符的解决方案。

There are two other solutions to do this: Using JavaScript or styling a link to look like a button.

有两种其他解决方案可以做到这一点:使用 JavaScript 或将链接样式化为看起来像一个按钮。

Using JavaScript:

使用 JavaScript:

<button onclick="window.location.href='/page2'">Continue</button>

But this obviously requires JavaScript, and for that reason it is less accessible to screen readers. The point of a link is to go to another page. So trying to make a button act like a link is the wrong solution. My suggestion is that you should use a link and style it to look like a button.

但这显然需要 JavaScript,因此屏幕阅读器不太容易访问它。链接的目的是转到另一个页面。所以试图让按钮像链接一样是错误的解决方案。我的建议是您应该使用链接并将其样式设置为看起来像一个按钮

<a href="/link/to/page2">Continue</a>

回答by BalusC

HTML

HTML

The plain HTML way is to put it in a <form>wherein you specify the desired target URL in the actionattribute.

普通的 HTML 方法是将它放在<form>您在action属性中指定所需目标 URL 的地方。

<form action="https://google.com">
    <input type="submit" value="Go to Google" />
</form>

If necessary, set CSS display: inline;on the form to keep it in the flow with the surrounding text. Instead of <input type="submit">in above example, you can also use <button type="submit">. The only difference is that the <button>element allows children.

如有必要,display: inline;在表单上设置 CSS以使其与周围的文本保持一致。除了<input type="submit">上面的例子,你也可以使用<button type="submit">. 唯一的区别是该<button>元素允许子元素。

You'd intuitively expect to be able to use <button href="https://google.com">analogous with the <a>element, but unfortunately no, this attribute does not exist according to HTML specification.

您会直觉地希望能够使用<button href="https://google.com"><a>元素类似的功能,但不幸的是,没有,根据HTML 规范,此属性不存在。

CSS

CSS

If CSS is allowed, simply use an <a>which you style to look like a button using among others the appearanceproperty (it's only not supported in Internet Explorer).

如果允许使用 CSS,只需使用<a>您的样式使其看起来像使用该appearance属性的按钮(它仅在 Internet Explorer 中不受支持)。

<a href="https://google.com" class="button">Go to Google</a>
a.button {
    -webkit-appearance: button;
    -moz-appearance: button;
    appearance: button;

    text-decoration: none;
    color: initial;
}

Or pick one of those many CSS libraries like Bootstrap.

或者从众多 CSS 库中选择一个,比如Bootstrap

<a href="https://google.com" class="btn btn-primary">Go to Google</a>

JavaScript

JavaScript

If JavaScript is allowed, set the window.location.href.

如果允许使用 JavaScript,请设置window.location.href.

<input type="button" onclick="location.href='https://google.com';" value="Go to Google" />

Instead of <input type="button">in above example, you can also use <button>. The only difference is that the <button>element allows children.

除了<input type="button">上面的例子,你也可以使用<button>. 唯一的区别是该<button>元素允许子元素。

回答by Adam

<button onclick="location.href='http://www.example.com'" type="button">
         www.example.com</button>

Note that the type="button"attribute is important, since its missing value default is the Submit Button state.

请注意,该type="button"属性很重要,因为它的缺失值默认是 Submit Button state

回答by Bern

If it's the visual appearance of a button you're looking for in a basic HTML anchor tag then you can use the Twitter Bootstrapframework to format any of the following common HTML type links/buttons to appear as a button. Please note the visual differences between version 2, 3 or 4 of the framework:

如果它是您在基本 HTML 锚标记中寻找的按钮的视觉外观,那么您可以使用Twitter Bootstrap框架来格式化以下任何常见的 HTML 类型链接/按钮以显示为按钮。请注意框架版本 2、3 或 4 之间的视觉差异:

<a class="btn" href="">Link</a>
<button class="btn" type="submit">Button</button>
<input class="btn" type="button" value="Input">
<input class="btn" type="submit" value="Submit">

Bootstrap (v4)sample appearance:

Bootstrap (v4)示例外观:

Sample output of Boostrap v4 buttons

Boostrap v4 按钮的示例输出

Bootstrap (v3)sample appearance:

Bootstrap (v3)示例外观:

Sample output of Boostrap v3 buttons

Boostrap v3 按钮的示例输出

Bootstrap (v2)sample appearance:

Bootstrap (v2)示例外观:

Sample output of Boostrap v2 buttons

Boostrap v2 按钮的示例输出

回答by RedFilter

Use:

用:

<a href="http://www.stackoverflow.com/">
    <button>Click me</button>
</a>

Unfortunately, this markup is no longer valid in HTML5 and will neither validate nor always work as potentially expected. Use another approach.

不幸的是,此标记在 HTML5 中不再有效,并且既不会验证也不会始终如预期的那样工作。使用另一种方法。

回答by EternalHour

As of HTML5, buttons support the formactionattribute. Best of all, no Javascript or trickery is needed.

从 HTML5 开始,按钮支持该formaction属性。最重要的是,不需要 Javascript 或技巧。

<form>
  <button formaction="http://stackoverflow.com">Go to Stack Overflow!</button>
</form>

Caveats

注意事项

  • Must be surrounded by <form>tags.
  • <button>type must be "submit" (or unspecified), I couldn't get it working with type "button." Which brings up point below.
  • Overrides the default action in a form. In other words, if you do this inside another form it's going to cause a conflict.
  • 必须被<form>标签包围。
  • <button>类型必须是“提交”(或未指定),我无法使用“按钮”类型。这提出了下面的观点。
  • 覆盖表单中的默认操作。换句话说,如果你在另一种形式中这样做,就会引起冲突。

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formactionBrowser Support: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Browser_compatibility

参考:https: //developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formaction浏览器支持:https: //developer.mozilla.org/en-US/docs/Web/ HTML/元素/按钮#Browser_compatibility

回答by Lucian Minea

It is actualy very simple and without using any form elements. You can just use the <a> tag with a button inside :).

它实际上非常简单并且不使用任何表单元素。您可以使用带有按钮的 <a> 标签:)。

Like this:

像这样:

<a href="http://www.google.com" target="_parent"><button>Click me !</button></a>

And it will load the href into the same page. Want a new page? Just use target="_blank".

它会将 href 加载到同一页面中。想要一个新页面?只需使用target="_blank".

EDIT

编辑

Couple of years later, while my solution still works, keep in mind you can use a lot of CSS to make it look whatever you want. This was just a fast way.

几年后,虽然我的解决方案仍然有效,但请记住,您可以使用大量 CSS 使其看起来随心所欲。这只是一个快速的方法。

回答by saravanabawa

If you are using an inside form, add the attribute type="reset"along with the button element. It will prevent the form action.

如果您使用的是内部表单,请将属性type="reset"与按钮元素一起添加。它将阻止表单操作。

<button type="reset" onclick="location.href='http://www.example.com'">
    www.example.com
</button>

回答by ghoppe

<form>
    <input TYPE="button" VALUE="Home Page"
        onclick="window.location.href='http://www.wherever.com'"> 
</form>

回答by Nicolas Bouvrette

There seems to be three solutions to this problem (all with pros and cons).

这个问题似乎有三种解决方案(各有利弊)。

Solution 1: Button in a form.

解决方案 1:表单中的按钮。

<form method="get" action="/page2">
    <button type="submit">Continue</button>
</form>

But the problem with this is that in some version of popular browsers such as Chrome, Safari and Internet Explorer, it adds a question mark character to the end of the URL. So in other words for the code above your URL will end up looking like this:

但问题在于,在某些版本的流行浏览器(例如 Chrome、Safari 和 Internet Explorer)中,它会在 URL 末尾添加一个问号字符。因此,换句话说,对于上面的代码,您的 URL 最终将如下所示:

http://someserver/pages2?

There is one way to fix this, but it will require server-side configuration. One example using Apache Mod_rewritewould be to redirect all requests with a trailing ?to their corresponding URL without the ?. Here is an example using .htaccess, but there is a full thread here:

有一种方法可以解决这个问题,但它需要服务器端配置。使用Apache Mod_rewrite 的一个示例是将所有带有尾随的请求重定向?到其相应的 URL,而不带?. 下面是使用的.htaccess的例子,但有一个完整的线程在这里

RewriteCond %{THE_REQUEST} \?\ HTTP [NC]
RewriteRule ^/?(index\.cfm)? /? [R=301,L]

Similar configurations can vary depending on the webserver and stack used. So a summary of this approach:

类似的配置可能会因所使用的网络服务器和堆栈而异。所以总结一下这个方法:

Pros:

优点:

  1. This is a real button, and semantically it makes sense.
  2. Since it is a real button, it will also act like a real button (e.g. draggable behavior and/or mimic a click when pressing space bar when active).
  3. No JavaScript, no complex style required.
  1. 这是一个真正的按钮,从语义上讲是有道理的。
  2. 因为它是一个真正的按钮,它也将像一个真正的按钮一样工作(例如,可拖动行为和/或在活动时按下空格键时模仿点击)。
  3. 没有 JavaScript,不需要复杂的样式。

Cons:

缺点:

  1. Trailing ?looks ugly in some browsers. This can be fixed by a hack (in some cases) using POST instead of GET, but the clean way is to have a server-side redirect. The downside with the server side redirect is that it will cause an extra HTTP call for these links because of the 304 redirect.
  2. Adds extra <form>element
  3. Element positioning when using multiple forms can be tricky and becomes even worse when dealing with responsive designs. Some layout can become impossible to achieve with this solution depending on the order of the elements. This can end up impacting usability if the design is impacted by this challenge.
  1. 拖尾?在某些浏览器中看起来很难看。这可以通过使用 POST 而不是 GET 的 hack(在某些情况下)来修复,但干净的方法是使用服务器端重定向。服务器端重定向的缺点是,由于 304 重定向,它会导致对这些链接的额外 HTTP 调用。
  2. 添加额外<form>元素
  3. 使用多个表单时的元素定位可能会很棘手,并且在处理响应式设计时会变得更糟。根据元素的顺序,使用此解决方案可能无法实现某些布局。如果设计受到此挑战的影响,这最终可能会影响可用性。

Solution 2: Using JavaScript.

解决方案 2:使用 JavaScript。

You can use JavaScript to trigger onclick and other events to mimic the behavior of a link using a button. The example below could be improve and remove from the HTML, but it is there simply to illustrate the idea:

您可以使用 JavaScript 触发 onclick 和其他事件来模拟使用按钮的链接的行为。下面的示例可以改进并从 HTML 中删除,但它只是为了说明这个想法:

<button onclick="window.location.href='/page2'">Continue</button>

Pros:

优点:

  1. Simple (for basic requirement) and keep semantic while not requiring an extra form.
  2. Since it is a real button, it will also act like a real button (e.g. draggable behavior and/or mimic a click when pressing space bar when active).
  1. 简单(对于基本要求)并保持语义,同时不需要额外的形式。
  2. 因为它是一个真正的按钮,它也将像一个真正的按钮一样工作(例如,可拖动行为和/或在活动时按下空格键时模仿点击)。

Cons:

缺点:

  1. Requires JavaScript which means less accessible. This is not ideal for a base (core) element such as a link.
  1. 需要 JavaScript,这意味着不易访问。这对于诸如链接之类的基本(核心)元素来说并不理想。

Solution 3: Anchor (link) styled like a button.

解决方案 3:锚(链接)样式像一个按钮。

Styling a link like a buttonis relatively easy and can provide similar experience across different browsers. Bootstrapdoes this, but it is also easy to achieve on your own using simple styles.

将链接设计成按钮样式相对容易,并且可以在不同浏览器中提供类似的体验。Bootstrap 可以做到这一点,但您也可以使用简单的样式轻松实现。

Pros:

优点:

  1. Simple (for basic requirement) and good cross-browser support.
  2. Does not need a <form>to work.
  3. Does not need JavaScript to work.
  1. 简单(对于基本要求)和良好的跨浏览器支持。
  2. 不需要<form>工作。
  3. 不需要 JavaScript 即可工作。

Cons:

缺点:

  1. Semantic is sort of broken, because you want a button that acts like a link and not a link that acts like a button.
  2. It will not reproduce all behaviors of solution #1. It will not support the same behavior as button. For example, links react differently when dragged. Also the "space bar" link trigger will not work without some extra JavaScript code. It will add a lot of complexity since browsers are not consistent on how they support keypressevents on buttons.
  1. 语义有点坏,因为你想要一个像链接一样的按钮,而不是一个像按钮一样的链接。
  2. 它不会重现解决方案#1 的所有行为。它不会支持与按钮相同的行为。例如,链接在拖动时反应不同。此外,如果没有一些额外的 JavaScript 代码,“空格键”链接触发器将无法工作。这将增加很多复杂性,因为浏览器在如何支持keypress按钮上的事件方面不一致。

Conclusion

结论

Solution #1 (Button in a form) seems like the most transparent for users with minimal work required. If your layout is not impacted by this choice and the server side tweak is feasible, this is a good option for cases where accessibility is the top priority (e.g. links on an error page or error messages).

解决方案#1(表单中的按钮)对于需要最少工作的用户来说似乎是最透明的。如果您的布局不受此选择的影响并且服务器端调整是可行的,那么对于可访问性是最优先考虑的情况(例如错误页面上的链接或错误消息),这是一个不错的选择。

If JavaScript is not an obstacle to your accessibility requirements, then solution #2 (JavaScript) would be preferred over #1 and #3.

如果 JavaScript 不是您的可访问性要求的障碍,那么解决方案 #2 ( JavaScript) 将优于 #1 和 #3。

If for some reason, accessibility is vital (JavaScript is not an option) but you are in a situation where your design and/or your server configuration is preventing you from using option #1, then solution #3 (Anchor styled like a button) is a good alternative solve this problem with minimal usability impact.

如果由于某种原因,可访问性很重要(JavaScript 不是一个选项),但您的设计和/或服务器配置阻止您使用选项 #1,那么解决方案 #3(锚样式类似于按钮)是一个很好的替代方案,以最小的可用性影响解决这个问题。

回答by C.Gadd

Why not just place your button inside of a reference tag e.g

为什么不把你的按钮放在一个引用标签内,例如

<a href="https://www.google.com/"><button>Next</button></a>

This seems to work perfectly for me and does not add any %20 tags to the link, just how you want it. I have used a link to google to demonstrate.

这对我来说似乎很完美,并且不会在链接中添加任何 %20 标签,就像你想要的那样。我使用了一个指向 google 的链接来演示。

You could of course wrap this in a form tag but it is not necessary.

您当然可以将其包装在表单标签中,但这不是必需的。

When linking another local file just put it in the same folder and add the file name as the reference. Or specify the location of the file if in is not in the same folder.

链接另一个本地文件时,只需将其放在同一文件夹中并添加文件名作为参考。或者如果 in 不在同一文件夹中,请指定文件的位置。

<a href="myOtherFile"><button>Next</button></a>

This does not add any character onto the end of the URL either, however it does have the files project path as the url before ending with the name of the file. e.g

这也不会在 URL 的末尾添加任何字符,但是在以文件名结尾之前,它确实将文件项目路径作为 url。例如

If my project structure was...

如果我的项目结构是...

.. denotes a folder - denotes a file while four | denote a sub directory or file in parent folder

.. 表示一个文件夹 - 表示一个文件,而四个 | 表示父文件夹中的子目录或文件

..public
|||| ..html
|||| |||| -main.html
|||| |||| -secondary.html

..公共
|||| ..html
|||| |||| -main.html
|||| |||| -secondary.html

If I open main.html the URL would be,

如果我打开 main.html,URL 将是,

http://localhost:0000/public/html/main.html?_ijt=i7ms4v9oa7blahblahblah

However, when I clicked the button inside main.html to change to secondary.html, the URL would be,

但是,当我单击 main.html 中的按钮更改为 secondary.html 时,URL 将是,

http://localhost:0000/public/html/secondary.html 

No special characters included at the end of the URL. I hope this helps. By the way - (%20 denotes a space in a URL its encoded and inserted in the place of them.)

URL 末尾不包含特殊字符。我希望这有帮助。顺便说一句 - (%20 表示 URL 中的一个空格,它被编码并插入它们的位置。)

Note: The localhost:0000 will obviously not be 0000 you'll have your own port number there.

注意: localhost:0000 显然不会是 0000 您将在那里拥有自己的端口号。

Furthermore the ?_ijt=xxxxxxxxxxxxxx at the end off the main.html URL, x is determined by your own connection so obviously will not be equal to mine.

此外,main.html URL 末尾的 ?_ijt=xxxxxxxxxxxxxxx,x 由您自己的连接决定,因此显然不会等于我的。


It might seem like I'm stating some really basic points but I just want to explain as best as I can. Thank you for reading and I hope this help someone at the very least. Happy programming.


看起来我在陈述一些非常基本的观点,但我只想尽可能地解释。感谢您的阅读,我希望这至少对某人有所帮助。快乐编程。