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

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


当前回答

创建一个充当链接的按钮是HTML设计者需要考虑的一项要求。最被接受的答案是使用表单中的按钮,不幸的是,有时只会在当前窗口中加载新链接-如果这是在电子邮件中,情况会很糟糕。

其他人提出JS、Bootstraps、CSS Styles等可能不可用或不允许。假设一个用例像电子邮件中的一个链接来确认它,并且你没有一个设计完整的基于html的电子邮件模板。您可以简单地使用链接,但添加一些内联样式,如下所示:

$htmlLink = 'https://stackoverflow.com/questions/2906582/';
"<a target='_blank' href='". $htmlLink ."' style='color: purple; font-size: 24px; font-weight: bold; border:2px purple solid; text-decoration: none;'>View This Answer</a>"

引号已经设置好,如果要在电子邮件标记中作为一行,可以在两端用点(.)连接。这只会使文本变大,周围有边框;不是很好,但保证不会像前面所说的那样加载页面。在解析文本和变量时假设Php。

其他回答

在浏览器控制台中键入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>

Use:

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

不幸的是,这种标记在HTML5中不再有效,既不能验证,也不能始终按预期工作。使用另一种方法。

您可以使用JavaScript:

<html><button onclick='window.location=“http://www.google.com"'>谷歌</按钮></html>

代替http://www.google.com并确保在URL之前包含http://。

另一个选项是在按钮中创建链接:

<button type="button"><a href="yourlink.com">Link link</a></button>

然后使用CSS来设置链接和按钮的样式,使链接占据按钮内的全部空间(这样用户就不会错过点击):

button, button a{position:relative;}
button a{top:0;left:0;bottom:0;right:0;}

我在这里创建了一个演示。

请记住,规范中说这是无效的,因为按钮不应包含任何交互式后代。

在JavaScript中

setLocation(base: string) {
  window.location.href = base;
}

HTML格式

<button onclick="setLocation('/<whatever>')>GO</button>"