Как кнопке указать ссылку html

Содержание
  1. Как создать HTML кнопку, которая действует как ссылка
  2. Добавьте строчный onclick event
  3. Пример
  4. Пример
  5. Используйте атрибут action или formaction внутри элемента .
  6. Пример
  7. Пример
  8. Пример
  9. Добавьте ссылку в стиле HTML кнопки (используя CSS)
  10. Пример
  11. How to Add an HTML Button that Acts Like a Link
  12. Add an inline onclick event
  13. Example of adding an onclick event to the tag:
  14. Example of adding an onclick event to the tag:
  15. Use the action or formaction attribute.
  16. Example of creating a button acting like a link with the action attribute:
  17. Example of opening a link from a button in a new window:
  18. Example of creating a button acting like a link with the formaction attribute:
  19. Style the link as a button
  20. Example of styling a link as a button with CSS:
  21. Example of styling a link as a button and adding a hover effect:
  22. How about the accessibility?
  23. HTML Button Link Code Examples – How to Make HTML Hyperlinks Using the HREF Attribute on Tags
  24. Why doesn’t this approach with the a element work?
  25. How to style a link to look like a button with CSS
  26. What are the issues with this approach?
  27. How to use the action and formaction attributes to make a button in a form
  28. How to use the action attribute
  29. How to use the formaction attribute
  30. Is this semantically correct?
  31. Side effects for using the action and formaction attributes
  32. How to use the JavaScript onclick event to make a button
  33. Drawbacks to this approach
  34. Conclusion

Как создать HTML кнопку, которая действует как ссылка

Есть много способов создания HTML кнопки, которая действует как ссылка, т.е., когда вы нажимаете на эту кнопку, она перенаправляется на указанный URL-адрес.

Читайте также:  Php возврат результата по ссылке

Вы можете выбрать один из следующих методов добавления ссылки на HTML кнопку.

Добавьте строчный onclick event

Пример

html> html> head> title>Заголовок документа title> head> body> button onclick="window.location.href = 'https://w3docs.com';">Click Here button> body> html>

Пример

html> html> head> title>Заголовок документа title> head> body> form> input type="button" onclick="window.location.href = 'https://www.w3docs.com';" value="w3docs"/> form> body> html>

Ссылки не будут работать, если JavaScript не используется, а поисковая система может проигнорировать такие ссылки.

Используйте атрибут action или formaction внутри элемента .

Пример

html> html> head> title>Заголовок документа title> head> body> form action="https://www.w3docs.com/"> button type="submit">Click me button> form> body> html>

Для того, чтобы открыть ссылку в новой вкладке, добавьте атрибут target=»_blank» .

Пример

html> html> head> title>Заголовок документа title> head> body> form action="https://www.w3docs.com/" method="get" target="_blank"> button type="submit">Click me button> form> body> html>

Так как нет форм и данных, этот пример семантически не будет иметь смысла. Но данная разметка допустима.

Пример

html> html> head> title>Заголовок документа title> head> body> form> button type="submit" formaction="https://www.w3docs.com">Click me button> form> body> html>

Атрибут formaction используется только для кнопок с type=”submit”. Так как этот атрибут является HTML5-specific, он может слабо поддерживаться в старых браузерах.

Добавьте ссылку в стиле HTML кнопки (используя CSS)

Пример

html> html> head> title>Заголовок документа title> style> .button < background-color: #FF4500; border: none; color: white; padding: 20px 34px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 2px; cursor: pointer; > style> head> body> a href="https://www.w3docs.com/" class="button">Click Here a> body> html>

Источник

Читайте также:  Php работа с видеофайлами

How to Add an HTML Button that Acts Like a Link

There are several ways of creating an HTML button, that acts like a link (i.e., clicking on it the user is redirected to the specified URL). You can choose one of the following methods to add a link to the HTML button.

Add an inline onclick event

You can add an inline onclick event to the tag.

Example of adding an onclick event to the tag:

html> html> head> title>Title of the document title> head> body> button onclick="window.location.href='https://w3docs.com';"> Click Here button> body> html>

It is also possible to add an inline onclick event to the tag within the element.

Example of adding an onclick event to the tag:

html> html> head> title>Title of the document title> head> body> form> input type="button" onclick="window.location.href='https://www.w3docs.com';" value="w3docs" /> form> body> html>

Use the action or formaction attribute.

Another way of creating a button that acts like a link is using the action or formaction attribute within the element.

Example of creating a button acting like a link with the action attribute:

html> html> head> title>Title of the document title> head> body> form action="https://www.w3docs.com/"> button type="submit">Click me button> form> body> html>

To open the link in a new tab, add target=»_blank» .

html> html> head> title>Title of the document title> head> body> form action="https://www.w3docs.com/" method="get" target="_blank"> button type="submit">Click me button> form> body> html>

Since there is no form and no data is submitted, this may be semantically incorrect. However, this markup is valid.

Example of creating a button acting like a link with the formaction attribute:

html> html> head> title>Title of the document title> head> body> form> button type="submit" formaction="https://www.w3docs.com">Click me button> form> body> html>

The formaction attribute is only used with buttons having type=»submit» . Since this attribute is HTML5-specific, its support in old browsers may be poor.

Add a link styled as a button with CSS properties. A href attribute is the required attribute of the tag. It specifies a link on the web page or a place on the same page where the user navigates after clicking on the link.

html> html> head> title>Title of the document title> style> .button < background-color: #1c87c9; border: none; color: white; padding: 20px 34px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 2px; cursor: pointer; > style> head> body> a href="https://www.w3docs.com/" class="button">Click Here a> body> html>

Let’s see one more example.

html> html> head> title>Title of the document title> style> .button < display: inline-block; padding: 10px 20px; text-align: center; text-decoration: none; color: #ffffff; background-color: #7aa8b7; border-radius: 6px; outline: none; transition: 0.3s; > .button:hover < background-color: #c2c7c7; > style> head> body> a class="button" href="https://www.w3docs.com/learn-html/html-button-tag.html">HTML button tag a> body> html>

How about the accessibility?

Let’s take accessibility into our account for the last example. Here are some improvements to make the code more accessible:

If the button contained an image, it would be important to provide an alt attribute to make the image accessible to screen readers. Since this button doesn’t have an image, we don’t need to worry about this.

Adding a label to the button will help users who rely on assistive technology understand the purpose of the button. We can do this by wrapping the button text in a element and adding an aria-label attribute to the button.

To improve visibility for users with low vision, we can increase the contrast between the text color and background color of the button. We can achieve this by making the background color darker or the text color lighter.

Adding a focus style to the button will help users who navigate using the keyboard to see which element is currently focused. We can add a simple border to the button to achieve this.

Here’s the updated code with these improvements:

html> html> head> title>Title of the document title> style> .button < display: inline-block; padding: 10px 20px; text-align: center; text-decoration: none; color: #ffffff; background-color: #3c5d6e; border-radius: 6px; outline: none; transition: 0.3s; border: 2px solid transparent; > .button:hover, .button:focus < background-color: #c2c7c7; border-color: #7aa8b7; > style> head> body> a class="button" href="https://www.w3docs.com/learn-html/html-button-tag.html" aria-label="Learn about the HTML button tag">span>HTML button tag span> a> body> html>

Источник

HTML Button Link Code Examples – How to Make HTML Hyperlinks Using the HREF Attribute on Tags

In this article, we are going to explore three different ways you can make an HTML button act like a link.

These are the methods we’ll go over:

  1. Styling a link to look like a button
  2. Using the action and formaction attributes in a form
  3. Using the JavaScript onclick event

But first, let’s take a look at the wrong approach.

Why doesn’t this approach with the a element work?

The code snippet below leads to the freeCodeCamp website when it is clicked.

However, this is not valid HTML.

The a element can be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g., buttons or other links). — (Source: Web Hypertext Application Technology Working Group)

This is considered bad practice because it makes it unclear as to the user’s intent.

Links are supposed to navigate the user to another part of the webpage or an external site. And buttons are supposed to perform a specific action like submitting a form.

When you nest one inside the other, it makes it confusing as to what action you want performed. That is why it is best to not nest a button inside an anchor tag.

This first approach does not use the button at all. We can style an anchor tag to look like a button using CSS.

This is the default HTML styling for an anchor tag.

blue-anchor-tag

We can add a class to the anchor tag and then use that class selector to style the element.

If you wanted the link to open up a new page, you can add the target=»_blank» attribute like this:

Then, we can add a background color and change the font color like this:

background-and-white-text

The next step would be to add some padding around the text:

adding-padding-1

Lastly, we can use the text-decoration property to remove the underline from the text:

removing-underline

Now we have an anchor tag that looks like a button.

We can also make this «button» be a little more interactive by changing the background color depending on the state of the link.

bootstrap-styles

If your project already includes Bootstrap, then you can use the built-in button styles. But I would not import Bootstrap just to style one link.

What are the issues with this approach?

There is some debate whether it is good practice to style links as buttons. Some will argue that links should always look like links and buttons should look like buttons.

In the web book titled Resilient Web Design, Jeremy Keith states that

Why did I bother to bring up this debate?

My goal is not to make you choose one side of the debate over another. I just want you to be aware of this ongoing discussion.

How to use the action and formaction attributes to make a button in a form

How to use the action attribute

Another alternative would be to nest the button inside a form and use the action attribute.

This would be the default button style.

default-button-style

We could use the same styles as earlier, but we would have to add the cursor pointer and set the border to none, like this:

removing-underline-1

How to use the formaction attribute

Similar to the previous approach, we can create a form and use the formaction attribute.

You can only use the formaction attribute with inputs and buttons that have type=»image» or type=»submit» .

Is this semantically correct?

While this appears to be a working solution, there is a question if this is semantically correct.

We are using the form tags but this does not function like a real form. The purpose of a form is to collect and submit user data.

But we are using the submit button to navigate the user to another page.

When it comes to semantics, this is a not a good way to use the form tags.

Side effects for using the action and formaction attributes

When you click on the button, something interesting happens with the URL. The URL now has a question mark at the end of it.

question-mark-at-end

The reason for this change is because the form is using the GET method. You could switch to the POST method, but there might be cases where that is not ideal either.

While this approach is valid HTML, it does come with this unintended side effect.

How to use the JavaScript onclick event to make a button

In the previous approaches, we have looked at HTML and CSS solutions. But we can also use JavaScript to achieve the same result.

The location.href represents the location of a specific URL. In this case, Window.location.href will return https://www.freecodecamp.org/.

Drawbacks to this approach

While this solution does work, there are some potential issues to consider.

If the user has decided to disable JavaScript in their browser, then clearly this solution would not work. Unfortunately, that could lead to a poor user experience.

Conclusion

The goal of this article was to show you three different ways you can make buttons act like links.

The first approach was to design a link to look like a button. We also looked into the debate whether it is a good idea to change the appearance of links to look like another element.

The second approach used the form and formaction attributes. But we also learned that this approach has some side effects with the URL and is not semantically correct.

The third approach used the JavaScript onclick event and the Window.location.href. But we also learned that this approach might not work if the user decides to disable JavaScript in their browser.

As a developer, it is really important to look at the pros and cons of a particular approach before incorporating it into your project.

I hope you enjoyed this article and learned a few things along the way.

Источник

Оцените статью