Всплывающая подсказка

Атрибуты и свойства элементов документа (HTML, XHTML)

Атрибут элемента HTML — это сущность, которая используется для определения характеристик html-элемента.

Атрибут элемента помещается внутри открытого тега элемента и состоит из двух частей:

  1. имя атрибута — это свойство элемента, которое вы хотите определить или изменить;
  2. значение — это значение, которое вы хотите установить для указанного выше свойства (значение атрибута всегда помещается в кавычки ).

< p align = "right" >Lorem ipsum dolor sit amet . < / p >// выравнивание абзаца по правому краю (align — имя атрибута, «right» — значение)

Имена и значения атрибутов в HTML не зависят от регистра, однако консорциум World Wide Web (W3C) рекомендует использовать атрибуты и значения атрибутов в нижнем регистре.

Атрибуты могут быть стандартными и нестандартными, причем стандартный атрибут для одного тега может быть нестандартным для другого . Например, атрибут «type» является стандартным для элемента (HTMLInputElement), но не является стандартным для (HTMLBodyElement).

Стандартные атрибуты описаны в спецификации для соответствующего класса элемента.

Когда браузер парсит HTML, чтобы создать DOM-объекты для тегов, он распознаёт стандартные атрибуты элементов документа и создаёт свойства объектов DOM для них.

Атрибуты элемента (в отличие от свойств элемента как объекта DOM):

  1. всегда являются строками (значение, присвоенное атрибуту, станет строкой);
  2. их имя нечувствительно к регистру (это HTML);
  3. видны в innerHTML .
Читайте также:  Java write to file encode

Источник

HTML attribute reference

Elements in HTML have attributes; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want.

Attribute list

Attribute Name Elements Description
accept , List of types the server accepts, typically a file type.
accept-charset List of supported charsets.
accesskey Global attribute Keyboard shortcut to activate or add focus to the element.
action The URI of a program that processes the information submitted via the form.
align Deprecated , , , , , , , , , , , , Specifies the horizontal alignment of the element.
allow Specifies a feature-policy for the iframe.
alt , , Alternative text in case an image can’t be displayed.
async Executes the script asynchronously.
autocapitalize Global attribute Sets whether input is automatically capitalized when entered by user
autocomplete , , , Indicates whether controls in this form can by default have their values automatically completed by the browser.
autoplay , The audio or video should play as soon as possible.
background , , , Specifies the URL of an image file.

Note: Although browsers and email clients may still support this attribute, it is obsolete. Use CSS background-image instead.

Background color of the element.

Note: This is a legacy attribute. Please use the CSS background-color property instead.

Note: This is a legacy attribute. Please use the CSS border property instead.

This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format.

Note: This is a legacy attribute. Please use the CSS color property instead.

Specifies the height of elements listed here. For all other elements, use the CSS height property.

Note: In some instances, such as , this is a legacy attribute, in which case the CSS height property should be used instead.

Specifies a Subresource Integrity value that allows browsers to verify what they fetch.

Note: This attribute is obsolete, use instead.

For the elements listed here, this establishes the element’s width.

Note: For all other instances, such as , this is a legacy attribute, in which case the CSS width property should be used instead.

Content versus IDL attributes

In HTML, most attributes have two faces: the content attribute and the IDL (Interface Definition Language) attribute.

The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via element.setAttribute() or element.getAttribute() . The content attribute is always a string even when the expected value should be an integer. For example, to set an element’s maxlength to 42 using the content attribute, you have to call setAttribute(«maxlength», «42») on that element.

The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like element.foo . The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes.

IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength , it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion.

IDL attributes can reflect other types such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow the rules laid out in the specification, but sometimes it doesn’t. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly ( select.size , for example) and you should read the specifications to understand how exactly they behave.

Boolean Attributes

Some content attributes (e.g. required , readonly , disabled ) are called boolean attributes. If a boolean attribute is present, its value is true, and if it’s absent, its value is false.

HTML defines restrictions on the allowed values of boolean attributes: If the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ASCII case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace. The following examples are valid ways to mark up a boolean attribute:

div itemscope>This is valid HTML but invalid XML.div> div itemscope=itemscope>This is also valid HTML but invalid XML.div> div itemscope="">This is valid HTML and also valid XML.div> div itemscope="itemscope"> This is also valid HTML and XML, but perhaps a bit verbose. div> 

To be clear, the values » true » and » false » are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether. This restriction clears up some common misunderstandings: With checked=»false» for example, the element’s checked attribute would be interpreted as true because the attribute is present.

Event handler attributes

Warning: The use of event handler content attributes is discouraged. The mix of HTML and JavaScript often produces unmaintainable code, and the execution of event handler attributes may also be blocked by content security policies.

In addition to the attributes listed in the table above, global event handlers — such as onclick — can also be specified as content attributes on all elements.

All event handler attributes accept a string. The string will be used to synthesize a JavaScript function like function name(/*args*/) , where name is the attribute’s name, and body is the attribute’s value. The handler receives the same parameters as its JavaScript event handler counterpart — most handlers receive only one event parameter, while onerror receives five: event , source , lineno , colno , error . This means you can, in general, use the event variable within the attribute.

div onclick="console.log(event)">Click me!div> div onclick="console.log(onclick)">Click me!div> 

Источник

HTML Атрибуты

Атрибуты задаются в начальном тэге элемента и состоят из имени и значения, которые отделяются друг от друга знаком равно (=). Например в атрибуте href=»http://www.wm-school.ru/» href является именем, а http://www.wm-school.ru/ значением.

HTML-теги могут содержать один или несколько атрибутов. Атрибуты добавляются в тег для того, чтобы информировать браузер о том, как данный тег должен отображаться в html-документе.

Атрибут title

Рассмотрим следующий пример:

Пример HTML:

В этом примере используется тег , который предназначен для обозначения аббревиатуры или акронима. В начальном теге элемента дополнительно был добавлен атрибут. Этот атрибут содержит заголовок для элемента.

Имя атрибута title. В этом примере, мы дали ему значение Язык гипертекстовой разметки .

Атрибут title может (необязательно) использоваться в любом HTML — элементе, чтобы предоставить дополнительную информацию о содержимом элемента.

При использовании атрибута title, большинство браузеров будет отображать его значение как «всплывающую подсказку», когда пользователь наводит указатель мыши на элемент.

Атрибут alt

Вы уже знаете, что изображения вставляются в Web-страницы с помощью одинарного тега . Атрибут alt добавляется внутрь тera и определяет для добавленноrо на WеЬ-страницу rpaфическоrо элемента альтернативный текст. Этот текст называется альтернативным, поскольку может отображаться на экране как альтернатива самому изображению.

В следующем примере вы увидите, как браузер работает с атрибутом alt, когда появляется «отсутствующее» изображение. Если рисунок не может быть найден или по какой-то причине не загружается, вместо него выводится значение атрибута alt. Поменяйте имя файла с изображением с orange.jpg на pencil.jpg. На самом деле такого файла не существует, поэтому вы получите «отсутствующее» изображение.

Пример HTML:

Атрибут href

Вы можете добавить сразу несколько атрибутов к элементу.

Пример HTML:

Атрибут href определяет расположение веб — страницы, на которую ведет ссылка.

Мы также используем атрибут title для того, чтобы обеспечить некоторую консультационную помощь для пользователя в виде всплывающей подсказки.

Указывать атрибуты можно только внутри открывающих тегов и если атрибутов несколько, то между ними ставится пробел. При этом нельзя в одном теге задавать два одинаковых атрибута, даже если у них разные значения, то есть дублировать их запрещено. Атрибуты, как и теги, нечувствительны к регистру, то есть их допустимо писать заглавными и строчными буквами. Значения атрибутов можно брать в необязательные двойные (» «) или одинарные кавычки(‘ ‘).

W3C рекомендует использовать кавычки в HTML, и требует применение кавычек для более строгих типов документов, таких как XHTML.

Иногда бывает необходимо использовать кавычки. В этом примере атрибут заголовка не будет отображаться правильно, так как в значении атрибута содержатся пробелы:

Пример HTML:

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

Одинарные или двойные кавычки?

Чаще всего в HTML используются «двойные кавычки», но вы можете использовать и ‘одинарные’. Иногда вам придется использовать одинарные кавычки, если в значении есть часть, которая отдельно должна быть заключена в кавычки:

Общие атрибуты

Ниже представлен список некоторых атрибутов, которые стандартны для большинства html-элементов:

Атрибут Значение Описание
align right, left, center Горизонтальное выравнивание тегов
valign top, middle, bottom Вертикальное вырвнивание тегов внутри HTML-элемента.
background URL Расположение фонового изображения
id Уникальное имя Уникальное имя для использования с каскадными таблицами стилей.
class правило класса или стиль класса Классифицирует элемент для использования с каскадными таблицами стилей.
width Числовое значение Определяет ширину таблиц, изображений или ячеек таблицы.
height Числовое значение Определяет высотуу таблиц, изображений или ячеек таблицы.
title Текст подсказки Текст, отображаемый во всплывающей подсказке.

Полный список всех атрибутов для каждого элемента HTML, указан в нашем справочнике: HTML Атрибуты.

Задачи

Первое итоговое задание 3

Вы познакомились с тегами, необходимыми для создания простейшей HTML-страницы, а также с атрибутами и их значениями, которые очень важны для корректного отображения документа, оптимизации и продвижения в поисковиках.

Пришло время повторить изученное и выполнить несложные задания:

Всплывающая подсказка

Сделайте всплывающую подсказку с текстом «Хороший сайт», который появляется когда вы наводите указатель мыши на абзац, как показано на рис. 1.

Рис. 1

       

title="Хороший сайт">wm-school.ru — сайт для разработчиков.

Размеры изображения

Измените размер изображения до 200 пикселей в ширину и 150 пикселей в высоту.

Источник

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