如何创建像链接一样的HTML按钮?因此,单击该按钮可将用户重定向到页面。

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


当前回答

从HTML5开始,按钮支持formaction属性。最重要的是,不需要JavaScript或诡计。

<表单><button formaction=“http://stackoverflow.com“>转到堆栈溢出!</button></form>

注意事项

必须由<form>标记包围。<button>类型必须是“submit”(或未指定)-我无法使用“button”类型。这引出了以下问题。重写表单中的默认操作。换句话说,如果在另一个表单中执行此操作,将导致冲突。

参考:formaction

浏览器支持:<button>:button元素

其他回答

Bootstrap方法也适用于Bulma。

<link rel=“stylesheet”href=“https://cdn.jsdelivr.net/npm/bulma@0.9.2/css/bulma.min.css“><a href=“https://www.stackoverflow.com“class=”button is primary“>堆栈溢出</a>

还可以使用按钮:

例如,在ASP.NET Core语法中:

// Some other tags
 <form method="post">
      <input asp-for="YourModelPropertyOrYourMethodInputName"
      value="@TheValue" type="hidden" />
      <button type="submit" class="link-button" formaction="/TheDestinationController/TheDestinationActionMethod">
      @(TextValue)
      </button>
  </form>
// Other tags...


<style>
       .link-button {
        background: none !important;
        border: none;
        padding: 0 !important;
        color: #20a8d8;
        cursor: pointer;
    }
</style>

在浏览器控制台中键入window.location并按Enter键。然后,您可以清楚地知道位置包含:

   hash: ""
   host: "stackoverflow.com"
   hostname: "stackoverflow.com"
   href: "https://stackoverflow.com/questions/2906582/how-to-create-an-html-button- 
   that-acts-like-a-link"
   origin: "https://stackoverflow.com"
   pathname: "/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link"
   port: ""
   protocol: "https:"

您可以从这里设置任何值。

因此,对于重定向另一个页面,可以使用链接设置href值。

   window.location.href = your link

在您的案例中:

   <button onclick="window.location.href='www.google.com'">Google</button>

七种方法:

使用window.location.href='URL'使用window.location.replace('URL')使用window.location=“URL”使用window.open(“URL”)使用window.location.assign('URL')使用HTML表单使用HTML定位标记

<!-- 使用window.location.href='URL'--><button onclick='window.location.href=“https://stackoverflow.com"'>单击我</按钮><!-- 使用window.location.replace('URL')--><button onclick='窗口位置替换(“https://stackoverflow.com")'>单击我</按钮><!-- 使用window.location=“URL”--><button onclick='window.location=“https://stackoverflow.com"'>单击我</按钮><!-- 使用window.open('URL')--><button onclick='窗口打开(“https://stackoverflow.com“,”_self“,”“,”)'>单击我</按钮><!-- 使用window.location.assign('URL')--><button onclick='窗口位置分配(“http://www.stackoverflow.com")'>单击我</按钮><!-- 使用HTML表单--><表单操作='https://stackoverflow.com'方法='get'><input-type='submit'value='Click-Me'/></form><!-- 使用HTML定位标记--><a href='https://stackoverflow.com'><button>单击我</button></a>

实现这一点的唯一方法(除了BalusC巧妙的表单想法!)是向按钮添加JavaScript onclick事件,这对可访问性不利。

您是否考虑过将普通链接设置为按钮样式?你不能用这种方式实现特定于操作系统的按钮,但这仍然是最好的IMO方式。