[ARIA] Create an Accessible Tooltip on a Text Input

Here we use HTML and CSS to create a stylish yet semantic tooltip on a form input. I am using aria-describedby to create a relationship with the input and the tooltip. Then I use CSS to style the tooltip and control when it appears or disappears both on hover and focus.

We use VoiceOver. To test that on a MacOS, use CMD + F5.

A few resources:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Egghead A11y Tooltips</title>
    <link
      href="https://fonts.googleapis.com/css?family=Montserrat"
      rel="stylesheet"
    />
    <style>
      body {
        font-family: "Montserrat", sans-serif;
        background: #eedbff;
        color: #6505cc;
      }

      form {
        max-width: 40em;
        margin: 1rem;
      }

      .a11y-input-tooltip {
        position: relative;
      }

      input[type="text"] {
        width: 100%;
        max-width: 100%;
        padding: 0.75rem;
        margin: 8px -2px 20px;
        box-sizing: border-box;
        border-radius: 4px;
        border: 2px solid rgba(101, 5, 204, 0.7);
        font-size: 1rem;
        min-height: 49px;
      }

      input[type="text"]:focus,
      input[type="text"]:hover {
        outline: none;
        box-shadow: 2px 2px 10px rgba(60, 0, 130, 0.5);
      }
      input[type="text"]:hover + [role="tooltip"] {
        visibility: visible;
        opacity: 1;
      }

      [role="tooltip"] {
        transition: opacity 0.2s 0.5s ease-in-out;
        visibility: hidden;
        opacity: 0;
        position: relative;
        background: #6505cc;
        color: #eedbff;
        padding: 0.5rem 0.75rem;
        border-radius: 5px;
      }
      [role="tooltip"]::after {
        content: "";
        position: absolute;
        left: 20px;
        top: -5px;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 5px solid #6505cc;
      }
    </style>
  </head>
  <body>
    <form>
      <label for="name">Name:</label>
      <span class="a11y-input-tooltip">
        <input type="text" id="name" aria-describedby="a11y-tooltip" />
        <span role="tooltip" id="a11y-tooltip"
          >Please write your first and last name.</span
        >
      </span>
    </form>
  </body>
</html>

原文地址:https://www.cnblogs.com/Answer1215/p/11976461.html