How to create a label inside an <input> element?

后端 未结 13 602
悲哀的现实
悲哀的现实 2021-01-29 22:54

I would like to insert a descriptive text inside an input element that disappers when the user click on it.

I know it is a very common trick, but I do not know how to do

13条回答
  •  悲&欢浪女
    2021-01-29 23:29

    The common approach is to use the default value as a label, and then remove it when the field gains the focus.

    I really dislike this approach as it has accessibility and usability implications.

    Instead, I would start by using a standard element next to the field.

    Then, if JavaScript is active, set a class on an ancestor element which causes some new styles to apply that:

    • Relatively position a div that contains the input and label
    • Absolutely position the label
    • Absolutely position the input on top of the label
    • Remove the borders of the input and set its background-color to transparent

    Then, and also whenever the input loses the focus, I test to see if the input has a value. If it does, ensure that an ancestor element has a class (e.g. "hide-label"), otherwise ensure that it does not have that class.

    Whenever the input gains the focus, set that class.

    The stylesheet would use that classname in a selector to hide the label (using text-indent: -9999px; usually).

    This approach provides a decent experience for all users, including those with JS disabled and those using screen readers.

提交回复
热议问题