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

后端 未结 30 3559
长发绾君心
长发绾君心 2020-11-21 04:18

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.

相关标签:
30条回答
  • 2020-11-21 05:06

    Try

    .abutton { 
      background: #bada55; padding: 5px; border-radius: 5px; 
      transition: 1s; text-decoration: none; color: black;
    }
    .abutton:hover { background: #2a2;  }
    <a href="https://example.com" class="abutton">Continue</a>

    0 讨论(0)
  • 2020-11-21 05:07

    You can simply put an a tag around the element:

    <a href="http://google.com" target="_blank">
    <button>My Button</button>
    </a>
    

    https://jsfiddle.net/hj6gob8b/

    0 讨论(0)
  • 2020-11-21 05:10

    Another option is to create a link in the button:

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

    Then use CSS to style the link and button, so that the link takes up the entire space within the button (so there's no miss-clicking by the user):

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

    I have created a demo here.

    0 讨论(0)
  • 2020-11-21 05:10

    You could also set the buttons type-property to "button" (it makes it not submit the form), and then nest it inside a link (makes it redirect the user).

    This way you could have another button in the same form that does submit the form, in case that's needed. I also think this is preferable in most cases over setting the form method and action to be a link (unless it's a search-form I guess...)

    Example:

    <form method="POST" action="/SomePath">
      <input type="text" name="somefield" />
      <a href="www.target.com"><button type="button">Go to Target!</button></a>
      <button type="submit">submit form</button>
    </form>

    This way the first button redirects the user, while the second submits the form.

    Be careful to make sure the button doesn't trigger any action, as that will result in a conflict. Also as Arius pointed out, you should be aware that, for the above reason, this isn't strictly speaking considered valid HTML, according to the standard. It does however work as expected in Firefox and Chrome, but I haven't yet tested it for Internet Explorer.

    0 讨论(0)
  • 2020-11-21 05:11

    <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.

    0 讨论(0)
  • 2020-11-21 05:12

    You can use javascript:

    <html>
    <button onclick='window.location = "http://www.google.com"'>
                Google
            </button>
    
    </html>

    Replace http://www.google.com with your website, make sure to include http:// before the URL.

    0 讨论(0)
提交回复
热议问题