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

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


当前回答

七种方法:

使用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>

其他回答

我在一个我目前正在开发的网站上使用了这个,效果很好!如果你也想要一些很酷的样式,我会把CSS放在这里。

输入[类型=“提交”]{背景色:白色;宽度:200px;边框:3px实心#c9c9c9;字体大小:24pt;边距:5px;颜色:#969696;}input[type=“submit”]:悬停{颜色:白色;背景色:#969696;过渡:颜色0.2s 0.05s容易;过渡:背景色0.2s 0.05s轻松;光标:指针;}<input type=“submit”name=“submit”onClick=“window.location=”http://example.com'">

一个正在工作的JSFiddle在这里。

Use:

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

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

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

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

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

只需将按钮放在参考标签内。,

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

这似乎非常适合我,并且没有添加任何%20标签到链接中,只是你想要的。我使用了一个到谷歌的链接来演示。

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

当链接另一个本地文件时,只需将其放在同一文件夹中并添加文件名作为引用即可。如果不在同一文件夹中,请指定文件的位置。

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

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

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

..表示文件夹\

表示文件而四|表示父文件夹中的子目录或文件

平民的|||| ..html格式|||||||-main.html|||||||-ssecondary.html

如果我打开main.html文件,

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

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

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

URL末尾不包含特殊字符。

顺便说一句-(%20表示URL中的一个空格,它编码并插入到它们的位置。)

注意:localhost:0000显然不是0000。您将有自己的端口号。

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

我似乎在陈述一些非常基本的观点,但我只想尽可能地解释清楚。