html - 如何创建一个类似于链接的 HTML 按钮?

如何创建一个类似于链接的 HTML 按钮?这样点击按钮就会将用户重定向到一个页面。

我希望它可以访问,并且在 URL 中使用最少的额外字符或参数。

最佳答案

HTML

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

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

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

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

CSS

如果允许使用 CSS,只需使用 <a>您可以使用 appearance 将其设置为看起来像一个按钮属性 (it's only not supported in 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;
}

或者选择众多 CSS 库之一,例如 Bootstrap .

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

JavaScript

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

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

而不是 <input type="button">在上面的例子中,你也可以使用 <button> .唯一的区别是 <button>元素允许 child 。

https://stackoverflow.com/questions/2906582/

相关文章:

html - RegEx 匹配除 XHTML 自包含标签之外的开放标签

javascript - 我应该将 <script> 标签放在 HTML 标记中的什么位

。使用哪个?">html -