Html href data target

: The Anchor element

The HTML element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.

Try it

Attributes

This element’s attributes include the global attributes.

Causes the browser to treat the linked URL as a download. Can be used with or without a filename value:

  • Without a value, the browser will suggest a filename/extension, generated from various sources:
    • The Content-Disposition HTTP header
    • The final segment in the URL path
    • The media type (from the Content-Type header, the start of a data: URL, or Blob.type for a blob: URL)
    • download only works for same-origin URLs, or the blob: and data: schemes.
    • How browsers treat downloads varies by browser, user settings, and other factors. The user may be prompted before a download starts, or the file may be saved automatically, or it may open automatically, either in an external application or in the browser itself.
    • If the Content-Disposition header has different information from the download attribute, resulting behavior may differ:
      • If the header specifies a filename , it takes priority over a filename specified in the download attribute.
      • If the header specifies a disposition of inline , Chrome and Firefox prioritize the attribute and treat it as a download. Old Firefox versions (before 82) prioritize the header and will display the content inline.

      The URL that the hyperlink points to. Links are not restricted to HTTP-based URLs — they can use any URL scheme supported by browsers:

      • Sections of a page with document fragments
      • Specific text portions with text fragments
      • Pieces of media files with media fragments
      • Telephone numbers with tel: URLs
      • Email addresses with mailto: URLs
      • While web browsers may not support other URL schemes, websites can with registerProtocolHandler()

      Hints at the human language of the linked URL. No built-in functionality. Allowed values are the same as the global lang attribute.

      A space-separated list of URLs. When the link is followed, the browser will send POST requests with the body PING to the URLs. Typically for tracking.

      How much of the referrer to send when following the link.

      • no-referrer : The Referer header will not be sent.
      • no-referrer-when-downgrade : The Referer header will not be sent to origins without TLS (HTTPS).
      • origin : The sent referrer will be limited to the origin of the referring page: its scheme, host, and port.
      • origin-when-cross-origin : The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
      • same-origin : A referrer will be sent for same origin, but cross-origin requests will contain no referrer information.
      • strict-origin : Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don’t send it to a less secure destination (HTTPS→HTTP).
      • strict-origin-when-cross-origin (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
      • unsafe-url : The referrer will include the origin and the path (but not the fragment, password, or username). This value is unsafe, because it leaks origins and paths from TLS-protected resources to insecure origins.

      The relationship of the linked URL as space-separated link types.

      Where to display the linked URL, as the name for a browsing context (a tab, window, or ). The following keywords have special meanings for where to load the URL:

      • _self : the current browsing context. (Default)
      • _blank : usually a new tab, but users can configure browsers to open a new window instead.
      • _parent : the parent browsing context of the current one. If no parent, behaves as _self .
      • _top : the topmost browsing context (the «highest» context that’s an ancestor of the current one). If no ancestors, behaves as _self .

      Note: Setting target=»_blank» on elements implicitly provides the same rel behavior as setting rel=»noopener» which does not set window.opener .

      Hints at the linked URL’s format with a MIME type. No built-in functionality.

      Deprecated attributes

      Hinted at the character encoding of the linked URL.

      Note: This attribute is deprecated and should not be used by authors. Use the HTTP Content-Type header on the linked URL.

      Used with the shape attribute. A comma-separated list of coordinates.

      Was required to define a possible target location in a page. In HTML 4.01, id and name could both be used on , as long as they had identical values.

      Note: Use the global attribute id instead.

      Specified a reverse link; the opposite of the rel attribute. Deprecated for being very confusing.

      The shape of the hyperlink’s region in an image map.

      Источник

      Target = «_blank» и другие значения атрибута target

      target strong»>target HTML ? Почему он должен быть blank ? И самое интересное, почему вначале стоит подчеркивание? Давайте подробнее рассмотрим этот код и разберемся, что он делает.

      Атрибут target

      По умолчанию ссылки открываются в том же окне, в котором они были нажаты. Но иногда нужно, чтобы они открывались в новом окне. Это можно сделать, используя атрибут HTML target blank .

      Значения target

      Четыре наиболее распространенных значения атрибута target :

      _self

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

      Единственная ситуация, в которой это может произойти, если в HTML использован тег , который устанавливает определенный способ открытия для всех ссылок. Например, если между тегами добавлен следующий код , нужно использовать target=»_self» , чтобы ссылка открывалась в том же окне.

      _blank

      Открывает ссылку в новой вкладке или окне. Это определяется локальными настройками пользователя, в большинстве браузеров это новая вкладка. Вы можете подумать, что с помощью данного значения можно реализовать всплывающие рекламные блоки. Но это не так. Чаще всего для этого используется JavaScript , а не HTML .

      Это значение атрибута target HTML лучше всего использовать для открытия на новой вкладке ссылок на внешние сайты или на PDF-файлы . Благодаря этому после закрытия этих вкладок пользователь снова попадает на ваш сайт. Но этим не следует злоупотреблять, так как пользователю будет довольно сложно ориентироваться, если каждая ссылка будет открываться на новой вкладке.

      _parent

      Значение _parent открывает ссылку в родительском фрейме для фрейма, в котором вы находитесь. Это не популярное значение, так как теги для создания фреймов и не поддерживаются в HTML5 . Тем не менее, это значение по-прежнему можно использовать внутри тегов .

      _top

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

      framename

      Открывает ссылку во фрейме с именем, указанным в значении атрибута HTML href target . Например, открывается во фрейме с именем frame1 , то есть . iframe также поддерживают это значение атрибута. Но вряд ли вы когда-нибудь столкнетесь с такими вариантами использования. Когда framename выбирается пользователем, это имя может начинаться только с буквы, а не с цифры или другого символа.

      Символ подчёркивания

      Теперь разберемся, для чего используется символ нижнего подчеркивания. Если мы уберем подчеркивание и изменим значение атрибута на target=»blank» , то ссылка будет открываться в новом окне независимо от подчеркивания. Чтобы убедиться в этом, создайте новый HTML-документ и разместите на нем код следующей ссылки:

      Затем добавьте в документ код следующей ссылки. А теперь при открытой вкладке с первой ссылкой откройте вторую с атрибутом HTML target blank :

      Вы увидите, что вторая ссылка открылась во вкладке, которая была открыта для предыдущей ссылки, а не в новой ( собственной вкладке ).

      Это связано со значением framename , которое мы рассматривали ранее. Поскольку мы начали значение с буквы, “ blank ” интерпретируется как значение типа framename . В случае если framename указан в качестве цели, но такой фрейм не существует, новая вкладка или окно будет создано с использованием этого имени. Таким образом, новое окно, которое мы открыли ранее, стало фреймом с именем “ blank ”.

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

      Источник

      HTML Атрибут target

      Атрибут target (от англ. «target» — «цель, мишень») указывает место (фрейм или окно браузера) в которое должен быть загружен, указанный ресурс.

      Для элемента определяет имя фрейма, в котором будут открываться все ссылки.
      Действие target в качестве атрибута элемента распространяется на все ссылки документа, кроме ссылок в которых это действие переопределяется собственными атрибутами target .

      Для элемента определяет указывает место (фрейм или окно браузера) в которое должен быть загружен ответ сервера (результат отправки данных формы).

      Синтаксис

      Значения

      _blank Загружает страницу в новую вкладку браузера. _self Загружает страницу в текущую вкладку. _parent Загружает страницу во фрейм-родитель; если фреймов нет, то это значение работает как _self . _top Отменяет все фреймы и загружает страницу в полном окне браузера; если фреймов нет, то это значение работает как _self .

      Значение по умолчанию

      Применяется к тегам

      Отличия HTML 4.01 от HTML 5

      В HTML 4.01 атрибут считался устаревшим и не рекомендован к использованию, в HTML 5 он полностью поддерживается.

      Примеры использования:

      Атрибут target (Элемент )

      Пример HTML:

      Открыть пример в фрейме

      Атрибут target (Элемент )

      Пример HTML:

       Карта изображений  

      Источник

      HTML target Attribute

      The target attribute specifies where to open the linked document:

      Definition and Usage

      The target attribute specifies where to open the linked document.

      Browser Support

      Syntax

      Attribute Values

      Value Description
      _blank Opens the linked document in a new window or tab
      _self Opens the linked document in the same frame as it was clicked (this is default)
      _parent Opens the linked document in the parent frame
      _top Opens the linked document in the full body of the window
      framename Opens the linked document in the named iframe

      ❮ HTML tag

      Unlock Full Access 50% off

      COLOR PICKER

      colorpicker

      Join our Bootcamp!

      Report Error

      If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

      Thank You For Helping Us!

      Your message has been sent to W3Schools.

      Top Tutorials
      Top References
      Top Examples
      Get Certified

      W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

      Источник

      Читайте также:  Serialize to xml in java
Оцените статью