Атрибут longdesc в HTML
Learn HTML Code, Tags & CSS
Sharing is caring!
Code Example
What is longdesc for?
The alt description may not provide enough space for a complete description of an image. The longdesc attribute attempts t provide a solution to that problem, without packing information into the markup, by allowing the document author to link to another page or resource which provides the description. The content of a longdesc attribute must be a URL, not the description itself.
Status of the longdesc
The longdesc attribute was a part of the HTML 4.0 specification. When HTML5 was first published, it was labelled as “obsolete.” Later, it was released as a recommended “HTML Extension.” So it is sort-of deprecated, and sort-of available for use. As of this writing, no mainstream browsers support it, so using it will have no effect on your page.
Why should you use longdesc ?
Accessibility. Not everyone uses with the internet the same way you do. The blind and visually impaired use specialized browsers and text-to-voice screen readers to interact with web pages that are increasingly focused on a visual interface. Providing a longdesc resource that describes the content of an image can make you site much more accessible, especially if your content is heavily dependent on images.
Other reasons
Some people believe that using longdesc attributes can help with SEO. There is no evidence that this is the case, but it certainly can’t hurt. It is also possible that, if use of longdesc for accessibility becomes more prevalent, that Google and other search engines will begin use it. There was a time when Google didn’t care what your page looked like. Then, one day, it started taking page design into account. For a while, they didn’t care whether your site worked well on mobile phones or not. Now, sites that break on small screens are penalized. It is possible that Google will one day care about accessibility. Implementing best practices for accessibility on your site is good for visually impaired users now, and may be additionally good for you in the future.
Implementing longdesc
The value of the longdesc attribute must be a URL. But there are some options:
- Full URL of an external resource (a page on another site)
- Relative URL to an internal resource (another page on your site)
- ID-based URL to an element on the current page ( #element-id )
- Data URI (an encoded version of the actual description content)
External Resource
This is relatively easy if your image is a well-known art work, or the content is something which might have an authoritative resource location (i.e. a Wikipedia article). Simply link to the article.
Internal Resource
The markup for this isn’t any more complicated, but it does require you to create a separate page for each image longdesc . Content Management Systems like WordPress can make this easy because there is usually an HTML page for each attachment.
On-page element
This is a great approach, and lets you actually use the description as on-page content. You can display the description as simply part of your content (conventional browser users might want to read it), and simply identify the description text with an element id. Then link to that id in the longdesc attribute.
A single pink flamingo, in closeup, with a dark background of leaves and bushes. The flamingo has its head turned slightly to its left, so you can only see the right side of its face. The image is close-in, cutting out the flamingo’s legs and lower torso.
If the description would not be terribly useful for “regular” visitors, you can simply hide it with CSS.
Data URI
It is possible to encode entire pieces of complete content into a data string which browsers can “understand,” and then use that encoded string to display the content. This is most often done with images, but can also be done with entire documents or large blocks of text. This is the only way to actually include the description content into the longdesc attribute.
You need a special encoder to create data URIs. The one above was created with this tool.
Mixing it Up With JavaScript
Perhaps the most “complete” option would be to use a hidden, onpage longdesc element and then use JavaScript to allow the user to view it. Many people think this is essentially how browsers should implement the longdesc recommendation, so it seems like a good idea to just go ahead and implement this now. (One such project implementing this kind of functionality is Dirk Ginader’s Accessible-LongDesc, which uses and displays the longdesc content in an overlay on top of the image.
Должен ли HTML файл, на который указывает атрибут longdesc (назначенный тегу img), содержать любую разметку?
1 24ma13wg [2013-12-04 17:02:00]
Должен ли HTML файл, на который указывает атрибут longdesc (назначенный тегу img), содержать какую-либо разметку или должен быть только текст (не обернутый в любые теги)?
4 ответа
0 Решение unor [2013-12-07 04:43:00]
В описании изображения ДОЛЖНО быть включена богатая разметка (например, HTML5).
Связанное описание ДОЛЖНО находиться в широкодоступном формате.
Мне это непонятно, если требование о структурированной разметке предназначено только для исполнителей или если оно влияет и на авторов. Если речь идет о авторах, использование обычного текстового документа не будет разрешено, поскольку они не содержат «богатую разметку» (если. ну, это зависит от определения богатой разметки). Но я предполагаю, что это требование предназначено только для людей, реализующих longdesc (например, в CMS).
«Широкодоступный формат» также не очень хорошо определен.
Думаю, в конце концов, должно быть хорошо, чтобы ссылаться на документ, доступ к которому пользователи могут получить. Очевидно, что HTML будет довольно безопасной ставкой. Также должен работать простой текстовый документ, если он не содержит сложного описания, которое потребует структурированной разметки (см. Строки «Требуется» в примерах использования примера).
В расширении спецификации HMTL5 для longdesc есть несколько вариантов, но самое простое — описать их как страницу.
Т.е. из изображения longdesc наведите отдельную страницу, содержащуюся только для описания изображения. Поскольку поддержка пользовательского агента довольно плохая, я бы также включил это как ссылку под изображением, которое идет на страницу описания.
Вы можете ссылаться на другие вещи (например, простой текст), но с использованием стандартной HTML-страницы в вашем обычном шаблоне хорошо (при условии, что шаблон разумно доступен).
0 albert [2013-12-05 01:04:00]
да. не всегда, но чаще всего longdesc будет использоваться слабовидящими пользователями. которые полагаются на устройства чтения с экрана. которые полагаются на контент, соответствующим образом выделенный, чтобы обеспечить наилучший возможный ux.
на мой взгляд, вы уже приняли правильное решение использовать longdesc, yay! большинство людей могут небрежно. так зачем же останавливаться? что могут пострадать несколько элементов
(использование будет варьироваться)?
0 508Ninja [2013-12-04 23:29:00]
W3C не указывает явно, может или не может содержать теги. Но учитывая, что он должен быть действительным URL, связанная страница должна позволять HTML-форматирование внутри него. Чтобы полностью избежать этой дилеммы, лучше поместить описание изображения на самой странице и связать его в «longdesc» С# anchor-name раздела.
HTML longdesc attribute
longdesc
The purpose of the HTML longdesc attribute is to specify a link to a long textual description for images, iframes and frames.
When used with img element, it complements alt attribute of img. When used with iframe and frame elements, it complements title attribute.
Supported elements
HTML longdesc attribute supports img, iframe and frame elements.
Syntax
Where ElementName is any supported elements.
Type of value
Value
Default value
There is no default value of HTML longdesc attribute.
Supported doctypes
When used with img element, HTML 4.01 strict, HTML 4.01 transitional, HTML 4.01 frameset. When used with iframe and frame elements, HTML 4.01 frameset.
Example of HTML longdesc attribute with img
Result
View this example in a separate browser window
Note
In the real world, usage of longdesc is rare with respect to img element. But writing a long description for iframe and frame is near appropriate.
Example of HTML longdesc attribute with frame
Result
View this example a separate browser window
Example of HTML longdesc attribute with iframe
Result
View this example in a separate browser window
Списки и изображения в HTML
Изображения в HTML
Изображения придают сайту уникальный вид, делают его более выразительным и привлекательным, а разработчику сайта позволяют расширить арсенал средств для управления дизайном. Определенную информацию, вроде графиков и схем, проще и нагляднее передать через рисунки, чем долго описывать, что к чему. Так что правильное использование изображений на сайте только улучшит его.
Форматы графических файлов
Большинство браузеров поддерживает только три графических формата: GIF, JPEG и PNG. Наиболее широкое распространение получили GIF и JPEG. Долгое время они являлись практически стандартами веб-изображений. Формат PNG появился достаточно недавно, и его популярность значительно уступает форматам GIF и JPEG. Распространение формата PNG сдерживается старыми версиями браузеров, а также недостаточной и неполной поддержкой возможностей PNG в новых версиях.
Каждый из этих трех форматов имеет свои преимущества и недостатки, так что вопрос выбора оптимального формата должен определяться в каждом конкретном случае индивидуально. Рассмотрим основные особенности данных графических форматов.
Формат GIF (Graphics Interchange Format , формат обмена графическими данными) – это растровый формат, использующий для хранения информации о цвете только 8 битов. Таким образом, цветовой диапазон ограничен 256 цветами, а для уменьшения размера графических файлов возможно сократить количество используемых цветов до 2. Формат GIF поддерживает один уровень прозрачности, однако поддерживает анимацию, что делает его популярным для создания баннеров и простой анимации.
Еще одно преимущество формата GIF заключается в чересстрочной развертке . При включении этой опции изображение будет постепенно увеличивать четкость по мере его загрузки. Таким образом, изображение появляется на экране почти сразу после начала загрузки страницы и, не дожидаясь полной загрузки, можно понять, что представлено на картинке.
Формат GIF целесообразно использовать в том случае, если цветовой диапазон исходных изображений не превышает 256 цветов, либо количество цветов может быть уменьшено без существенного ухудшения качества. Это, как правило, логотипы, иллюстрации с четкими краями, анимированные рисунки, изображения с большими площадями одноцветных областей, баннеры. Для полноцветных изображений, в том числе для фотографий, формат GIF мало применим. В этом случае лучше использовать другие форматы сжатия.
Формат JPEG ( Joint Photographic Experts Group — объединенная группа экспертов в области фотографии) поддерживает 24-битные цвета (т.е. около 16 миллионов цветов) и сохраняет яркость и оттенки цветов изображений. Формат предполагает сжатие с потерями: JPEG-сжатие основано на разложении изображений на составляющие, близкие к тем, которые используются в человеческом зрении при отбрасывании информации, не сказывающейся на зрительном восприятии образа. За счет этого достигается высокое сжатие изображений при незначительном ухудшении качества. Степень сжатия и качество изображений находятся в обратной зависимости: чем сильнее сжато изображение, тем ниже его качество (и, соответственно, размер графического файла). В отличие от форматов GIF и PNG формат JPEG не поддерживает прозрачность: при сохранении изображения в данном формате, прозрачные пикселы заполняются определенным цветом. Формат JPEG поддерживает технологию, известную под названием прогрессивный JPEG, при которой версия рисунка с низким разрешением появляется в окне просмотра до полной загрузки самого изображения.
JPEG хорошо подходит для изображений с богатой цветовой гаммой, плавным переходом цветов, для фотографий и изображений с градиентными областями. В силу особенностей алгоритма сжатия JPEG лучше не использовать для сжатия изображений, цветовая гамма которых ограничена несколькими цветами, изображений с мелким текстом, изображений, которые должны сохранить четкие границы или содержат мелкие детали.
Формат PNG ( Portable Network Graphics — переносимая сетевая графика ), призванный заменить формат GIF, является относительно новым. Формат PNG существует в двух вариантах: PNG-8 и PNG-24.
PNG-8 практически полностью аналогичен формату GIF, за исключением улучшенного сжатия и отсутствия возможности анимации. PNG-8 хорошо подходит для текста, логотипов, иллюстраций с четкими краями и изображений с градиентной прозрачностью.
PNG-24 аналогичен PNG-8, но использует 24-битную палитру цвета и, подобно формату JPEG, сохраняет яркость и оттенки цветов в фотографиях. А подобно GIF и формату PNG-8, сохраняет детали изображения как, например, в логотипах или иллюстрациях. Формат PNG-24 обладает рядом дополнительных преимуществ, таких как применение улучшенного сжатия, наличие альфа-прозрачности и гамма-коррекции и др.
PNG-24 рекомендуется выбирать для полноцветных изображений с четкими краями и мелкими деталями, изображений с мелким текстом, а также для изображений с прозрачными областями. При использовании формата PNG-24 для сжатия полноцветных изображений, он проигрывает формату JPEG в размере созданного файла, т.к. использует сжатие без потерь.
Включение изображений в HTML
Для вставки изображения в HTML-документ используется элемент IMG, имеющий два обязательных атрибута src и alt.
Атрибут alt содержит так называемый альтернативный текст , который будет отображаться, если по каким-либо причинам изображение недоступно. Кроме того, люди с недостатками зрения используют вспомогательные технологии для чтения веб-страниц. Эти технологии считывают содержимое атрибутов alt элементов IMG. Поэтому важно написать хороший альтернативный текст для описания содержимого изображения и поместить его в атрибут alt . Такой текст позволяет также получить текстовую информацию о рисунке при отключенной в браузере загрузке изображений. Поскольку загрузка изображения происходит после получения браузером информации о нем, то замещающий рисунок текст появляется раньше. По мере же загрузки текст будет сменяться изображением. Браузеры также отображают альтернативный текст в виде подсказки, появляющейся при наведении курсора мыши на изображение. В качестве значения параметра alt служит любая подходящая текстовая строка. Ее обязательно надо брать в двойные или одинарные кавычки. Этот атрибут крайне полезен как для доступности, так и для оптимизации поисковых машин.
Атрибут src задает адрес графического файла, который будет отображаться на веб-странице. В качестве значения принимается абсолютный или относительный адрес файла. К абсолютному адресу относится полный путь к ресурсу, включая протокол передачи данных , наименование сервера, а также имена всех каталогов, ведущих к файлу, например http://www.somewhere.com/images/image.jpg. Относительные адреса описывают местоположение файла относительно текущего каталога (например, «../../images/image.jpg») или корня каталогов сервера (например, «/images/image.jpg»). Если требуемый графический файл находится в том же каталоге, что и HTML-документ, его использующий, то в качестве значения аргумента src допустимо указать просто имя требуемого графического файла.
Фрагмент кода, использующий описанные аргументы, представлен ниже:
Результат выполнения данного кода представлен на рисунке 7.
HTML5 Image Description Extension ( longdesc )
W3C Recommendation 26 February 2015
Please check the errata for any errors or issues reported since publication.
Abstract
This specification defines a longdesc attribute (based on the longdesc attribute of HTML 4) to link descriptions to images in HTML5 content.
By allowing a hyperlink inside another one, this document explicitly redefines the HTML concept of hyperlink in a limited set of circumstances.
Status of This Document
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
This document was developed through the HTML Accessibility Task Force, and is published by the HTML Working Group with approval by the Protocols and Formats Working Group as a W3C Recommendation.
If you wish to make comments regarding this document, please send them to public-html-a11y@w3.org (subscribe, archives). All feedback is welcome. Bugs can also be filed directly into the W3C Bug tracker for this specification.
The implementation report is also available, showing that the Candidate Recommendation exit criteria were met.
No changes were done to this specification since the previous publication.
This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C’s role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
Table of Contents
Introduction
Text alternatives are used to make visual information accessible by describing the information or function represented in an image. The alt attribute is designed to provide a concise description or functional equivalent for an image. For some images and contexts, more detail is required to convey all the information contained in the image. The longdesc attribute is designed as a means to provide this level of detail.
HTML 4 provided a longdesc attribute for the img element that enabled a machine-discoverable description of an image to be linked to the image. This extension specification defines a longdesc attribute to provide that functionality for HTML5.
1. Conformance
All authoring guidelines, diagrams, examples, notes, and sections marked «informative» in this specification are informational. Everything else in this specification is «normative» as described in [QAFRAME].
The key words «must», «should», «should not» and «may» in this specification are to be interpreted as described in [ RFC2119 ].
1.1 Dependencies and Definitions
The Interface Definition Language ( >must be interpreted as required for conforming IDL fragments, as described in the Web IDL specification. [ WEBIDL ]
The terms «valid non-empty URL potentially surrounded by spaces», «hyperlink», and «reflect», used in this specification are defined in [ HTML5 ], although this specification modifies the semantics of the term «hyperlink» in allowing hyperlinks to be nested in certain specific circumstances.
This document uses the terms and in the sense of ensuring people with disabilities can use the Web. Further information is available, e.g. Introduction to Web Accessibility.
2. Use Cases and Requirements
The longdesc attribute gives authors a mechanism for referencing a long text description for images which cannot be adequately described using shorter description mechanisms, such as in the following use cases.
Use Cases
Requirements for an Image Description Functionality
3. The longdesc Attribute
This extension changes the definition of a hyperlink in HTML, by allowing a longdesc attribute to occur inside a hyperlink.
3.0 Implementation
3.0.1 Authors and Conformance Checkers
Zero or one longdesc attributes may be added to any img element.
The longdesc attribute must contain a valid non-empty URL potentially surrounded by spaces. The URL is a hyperlink to a description of the image that the parent img element represents.
The linked description should be in a broadly accessible format.
This section is informative
Best practices for checking descriptions of images are beyond the scope of this document, but there are many resources available. For further guidance authoring tool developers can consult e.g. Appendix A-3: Long text descriptions of [ATAG].
High quality implementation in authoring and content management tools is likely to include checking for common errors, such as including a description instead of a URL in the attribute, or pointing to a resource that is an image or plain text, which are often poor choices for a high-quality description. Additional examples of error checking and repair options can be found in Appendix B: Levels of Checking Automation and Appendix C: Levels of Repair Automation of [ATAG]
3.0.2 Authors
When a description is only part of the target document, authors should link to a container element in the target document that contains the entire description.
This section is informative
Note that while in some cases this will allow user agents to present the description, there will be cases where user agents cannot or do not automatically restrict the information presented to the container element.
This section is informative
Best practices for full descriptions of images are beyond the scope of this document, but there are many resources available.
Authors should not rely solely on longdesc where standards exist to provide direct, structured access.
This section is informative
For example a MathML version of mathematical content, or an SVG image that uses the accessibility features of SVG, can provide direct accessibility to users with appropriate technology. In such cases, it is appropriate to use those techniques in combination with longdesc.
3.0.3 User Agents
If the longdesc value is val >must make the link available to all users through the regular user interface(s).
If the longdesc value is val >must expose the longdesc to relevant APIs, especially accessibility-oriented APIs, in a manner most appropriate to the API.
This section is informative
What is most appropriate to an API will vary with the individual API. Some APIs (like MSAA) will need the text string which constitutes the URL of the longdesc value. Other APIs may provide an actionable interface.
User agents should enable users to discover when images in a page contain a long description.
This section is informative
longdesc can be present on an image within a hyperlink. This does not change the requirements on user agents, which must still enable the hyperlink to be followed.
Complete documentation of best practices for implementation is beyond the scope of this document. These notes are offered to help minimize the impact of common mistakes.
A common mistake in the past has been to use a description, instead of a URL that links to a description. Converting such values to data: URLs is a repair strategy for user agents that can help users to recover in cases where authors have made this mistake.
It is usually helpful when the behavior for finding, reading, and returning from a long description to the image described is a consistent experience.
Further information on making user agents accessible can be found in [UAAG].
3.1 Extension to the HTMLImageElement Interface
3.1.1 Attribute
The >must be a valid non-empty URL potentially surrounded by spaces. It defines a hyperlink to a detailed description of the image its parent HTMLImageElement represents.
The longDesc >must reflect the HTML content attribute longdesc .
This section is informative
image . longDesc [ = value ]
Returns a DOMString that represents the attribute’s contents.
Can be set, to replace the contents of the attribute with the given string.
A. Acknowledgements
This section is informative
Thanks to the HTML Working Group of the late 1990s for the original specification of longdesc, to those who have implemented it in various kinds of software, and to many many people involved with the development of HTML5 (including but not limited to those who discussed «ISSUE-30» in the HTML Working Group, the Protocols and Formats Working Group, the W3C Advisory Board, and around countless dinner tables, coffee breaks, and elsewhere) for the ideas, discussions and contributions that led to the initial draft of this specification. With the exception of Laura Carlson, who did far more very valuable work than it took to produce this specification, they are not individually named: the list might be larger than the content of the specification.
For specific comments and suggestions that led to improvements over successive drafts of this specification, thanks to the W3C’s HTML Accessibility Task Force, the W3C Internationalization Working Group, and to Jonathan Avila, Robin Berjon, James Craig, Paul Cotton, Steve Faulkner, John Foliot, Geoff Freed, Peter Gruzca, Richard Ishida, Anne van Kesteren, David MacDonald, Michelle McManus, Chris Mills, Jay Munro, Devarshi Pant, Marta Pawlowska, Silvia Pfeiffer, Wendy Seltzer, Leif Halvard Silli, Mathew Turvey, Klaas ‘Z4us’ V, and Boris Zbarsky. The code examples are rendered with Lea Verou’s prism tools. Any errors are despite, not as a result of, their efforts.
HTML | longdesc Attribute
The HTML longdesc Attribute is used to specify a page which contains the long description of the content of the frame.
Syntax:
Attribute Values:
- URL: It contains the value i.e URL which specifies the page which contains the long description of the content of the frame.
- An absolute URL:It poins to another website.
- A relative URL: It points to a file within a website.
Атрибут longdesc в HTML
Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object.
Syntax
HTML |
---|
JavaScript |