Атрибут «rel=»: что он собой представляет и для чего нужен

Использование сценариев для DSO

Объект recordset DSO может быть использован для написания довольно функциональных скриптов, обращающихся к
XML-данным. Напишем HTML-страницу, которая будет осуществлять поиск данных в связанном XML-документе по вхождению
указанной пользователем строки и отображать результаты поиска. Поиск будем производить в XML-документе, приведённом
выше в этой статье, а именно — в XML-документе, который мы отображали с помощью вложенных HTML-таблиц. Будем
разыскивать товары, у которых есть сорт того цвета, который указал пользователь. Вот текст HTML-документа:

<XML ID=»dsoPRODUCTS» SRC=»Sample.xml»></XML>
Color: <input type=»text» id=»SearchText»> <button onclick=»FindProducts()»>Search</button>
<hr>
Results:<p>
<div id=»ResultDiv» style=»color:navy»></div>
<script>
function FindProducts(){
    //получаем текст, введённый пользователем,
    //и преобразуем его в прописные буквы, чтобы искать без учёта регистра
    SearchString = SearchText.value.toUpperCase();
    //если пользователь не ввёл текст, отображаем сообщение о том,
    //что ничего не найдено, и завершаем работу
    if(SearchString == «»){
        ResultDiv.innerHTML = «<h3> &lt; No products found &gt; </h3>»;
        return;
    }
    //переходим в начало набора записей
    dsoPRODUCTS.recordset.moveFirst();
    //переменная, содержащая результаты поиска
    ResultHTML = «»;
    //цикл по записям (товарам)
    while(!dsoPRODUCTS.recordset.EOF){
        //получаем заголовок товара
        TitleString = dsoPRODUCTS.recordset.fields(«TITLE»).value;
        //получаем набор записей сортов товара
        Sorts = dsoPRODUCTS.recordset.fields(«SORT»).value;
        //переходим в начало набора записей сортов товара
        Sorts.moveFirst();
        //цикл по сортам товара
        while(!Sorts.EOF){
            //получаем цвет товара
            ColorString = Sorts.fields(«COLOR»).value
            //собственно поиск
            if(ColorString.toUpperCase().indexOf(SearchString) >= 0){
                //если нашли, пополняем строку результатов
                ResultHTML += «<h3>» + TitleString + «<h3><br>»
                //переходим в конец набора записей сортов товара, т.к. дальнейший перебор не нужен
                Sorts.moveLast();
            }
            //переходим к следующему сорту товара
            Sorts.moveNext();
        }//конец цикла по сортам товара
        //переходим к следующему товару
        dsoPRODUCTS.recordset.moveNext();
    }//конец цикла по записям (товарам)
    //если ничего не найдено, отображаем сообщение об этом
    if(ResultHTML == «») ResultDiv.innerHTML = «<h3> &lt; No products found &gt; </h3>»;
    //выводим строку результатов
    else ResultDiv.innerHTML = ResultHTML;
}
</script>

Приведённая выше HTML-страница содержит поле ввода текста для пользователя (с идентификатором «SearchText»), и
кнопку запуска поиска. При нажатии на кнопку запускается скрипт, использующий свойства и методы объекта recordset
DSO, который осуществляет поиск и выводит результаты в элемент HTML-страницы DIV (с идентификатором «ResultDiv»),
расположенный внизу страницы. Скрипт подробно прокомментирован и в дополнительных пояснениях не нуждается.

Людоговский Александр

2007 http://www.script-coding.com При любом использовании материалов сайта обязательна ссылка на него как на источник информации, а также сохранение целостности и авторства материалов.

12.3 Document relationships: the LINK element

<!ELEMENT  - O EMPTY               -- a media-independent link -->
<!ATTLIST LINK
                                -- , ,  --
             #IMPLIED  -- char encoding of linked resource --
                    #IMPLIED  -- URI for linked resource --
       #IMPLIED  -- language code --
            #IMPLIED  -- advisory content type --
               #IMPLIED  -- forward link types --
               #IMPLIED  -- reverse link types --
             #IMPLIED  -- for rendering on these media --
  >

Start tag: required, End tag:
forbidden

Attributes defined elsewhere

  • , ()
  • (), ()
  • ()
  • ( )
  • , , , , , , , , , ( )
  • , , , , ()
  • ()
  • ()
  • ()

This element defines a link. Unlike , it may only appear in the
section of a document, although it may appear any number of times. Although
has no content, it conveys relationship information that may be rendered by
user agents in a variety of ways (e.g., a tool-bar with a drop-down menu of
links).

This example illustrates how several definitions may appear in the
section of a document. The current document is «Chapter2.html». The
attribute specifies the relationship of the linked document with the current
document. The values «Index», «Next», and «Prev» are explained in the section
on .

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
  <TITLE>Chapter 2</TITLE>
  <LINK rel="Index" href="../index.html">
  <LINK rel="Next"  href="Chapter3.html">
  <LINK rel="Prev"  href="Chapter1.html">
</HEAD>
...the rest of the document...

12.3.1 Forward and reverse links

The and attributes play complementary roles — the
attribute specifies a forward link and the attribute specifies a reverse
link.

Consider two documents A and B.

Document A:       <LINK href="docB" rel="foo">

Has exactly the same meaning as:

Document B:       <LINK href="docA" rev="foo">

Both attributes may be specified simultaneously.

12.3.2 Links and external style sheets

When the element links an external style sheet to a document, the attribute specifies the style sheet language and the attribute specifies the intended rendering medium or media.
User agents may save time by retrieving from the network only those style
sheets that apply to the current device.

are further
discussed in the section on style sheets.

12.3.3 Links and search engines

Authors may use the element to provide a variety of information to
search engines, including:

  • Links to alternate versions of a document, written in another human
    language.
  • Links to alternate versions of a document, designed for different media,
    for instance a version especially suited for printing.
  • Links to the starting page of a collection of documents.

The examples below illustrate how language information, media types, and
link types may be combined to improve document handling by search engines.

In the following example, we use the attribute to tell search
engines where to find Dutch, Portuguese, and Arabic versions of a document.
Note the use of the attribute for the Arabic manual. Note also the
use of the attribute to indicate that the value of the
attribute for the element designating the French manual is in French.

<HEAD>
<TITLE>The manual in English</TITLE>
<LINK title="The manual in Dutch"
      type="text/html"
      rel="alternate"
      hreflang="nl" 
      href="http://someplace.com/manual/dutch.html">
<LINK title="The manual in Portuguese"
      type="text/html"
      rel="alternate"
      hreflang="pt" 
      href="http://someplace.com/manual/portuguese.html">
<LINK title="The manual in Arabic"
      type="text/html"
      rel="alternate"
      charset="utf-8"
      hreflang="ar" 
      href="http://someplace.com/manual/arabic.html">
<LINK lang="fr" title="La documentation en Fran&ccedil;ais"
      type="text/html"
      rel="alternate"
      hreflang="fr"
      href="http://someplace.com/manual/french.html">
</HEAD>

In the following example, we tell search engines where to find the printed
version of a manual.

<HEAD>
<TITLE>Reference manual</TITLE>
<LINK media="print" title="The manual in postscript"
      type="application/postscript"
      rel="alternate"
      href="http://someplace.com/manual/postscript.ps">
</HEAD>

In the following example, we tell search engines where to find the front
page of a collection of documents.

<HEAD>
<TITLE>Reference manual -- Page 5</TITLE>
<LINK rel="Start" title="The first page of the manual"
      type="text/html"
      href="http://someplace.com/manual/start.html">
</HEAD>

Further information is given in the notes in the appendix on .

Какими бывают состояния ссылок

Когда вы пишете стиль CSS, то с помощью селектора указываете, для какого элемента он предназначен. В самом начале учебника, когда мы изучали селекторы, в одном из уроков рассматривались псевдоклассы CSS, благодаря которым можно задавать стили для разных состояний элемента, в том числе для ссылок. Ниже — четыре состояния, которые могут принимать ссылки:

  • — ссылка, на которую наведен курсор;
  • — активная ссылка (та, по которой совершается клик, или на которой удерживается кнопка мыши);
  • — ссылка, еще не посещенная пользователем;
  • — посещенная ссылка.

Для справки: из соображений безопасности набор стилей, которые можно использовать для ссылок , ограничен. Посещенные ссылки принимают только свойства , , (и его производные), , . При этом свойство к посещенной ссылке можно применить, только если это же свойство задано и для обычной. Прозрачность цвета, установленная через альфа-канал для элемента , будет проигнорирована. JavaScript-метод getComputedStyle всегда возвращает значение цвета непосещенных ссылок, даже если у посещенных ссылок цвет иной.

Стилизация состояний

С помощью псевдокласса можно существенно изменить стиль ссылки, которая находится в состоянии наведенного на нее курсора. Простейший пример:

a { color: red; } /* обычный цвет ссылки */
a:hover { color: blue; } /* цвет ссылки, на которую наведен курсор */

Псевдокласс также поддается гибкой стилизации:

a:active { background-color: yellow; } /* цвет фона ссылки в момент нажатия на нее */

Если в ваши планы входит максимально детальная проработка дизайна ссылок, то желательно определить стили для всех четырех состояний

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

a:link { color: red; }
a:visited { color: grey; }
a:hover { color: blue; }
a:active { background-color: yellow; }

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

Выбор ссылок с помощью селекторов

Как записать селектор с псевдоклассом для определенной группы ссылок? Например, если вам нужно применить какой-то стиль для всех ссылок навигационного меню с идентификатором , когда такая ссылка находится в состоянии наведенного на нее курсора, вы можете использовать такой селектор:

#main-menu a:hover {background-color: #a38beb;}

Либо, если у каждой ссылки этого меню дополнительно имеется свой класс (допустим, это ), то такая запись тоже подойдет:

#main-menu a.menu-link:hover {background-color: #a38beb;}
#main-menu .menu-link:hover {background-color: #a38beb;} /* так тоже сработает */

Чтобы определить стили для всех состояний данных ссылок, запишите для каждого псевдокласса отдельное правило:

#main-menu .menu-link:link { color: red; }
#main-menu .menu-link:visited { color: grey; }
#main-menu .menu-link:hover { background-color: #a38beb; }
#main-menu .menu-link:active { background-color: yellow; }

Обширные возможности CSS в плане построения селекторов позволяют с удобством делать точную выборку ссылок, которые вам необходимо стилизовать. А какие именно свойства CSS применимы к ссылкам, мы обсудим в следующем уроке.

Linking Documents

A link is specified using HTML tag <a>. This tag is called anchor tag and anything between the opening <a> tag and the closing </a> tag becomes part of the link and a user can click that part to reach to the linked document. Following is the simple syntax to use <a> tag.

<a href = "Document URL" ... attributes-list>Link Text</a> 

Example

Let’s try following example which links http://www.tutorialspoint.com at your page −

<!DOCTYPE html>
<html>
   
   <head>
      <title>Hyperlink Example</title>
   </head>
	
   <body>
      <p>Click following link</p>
      <a href = "https://www.tutorialspoint.com" target = "_self">Tutorials Point</a>
   </body>
	
</html>

This will produce the following result, where you can click on the link generated to reach to the home page of Tutorials Point (in this example).

How to Embed CSS With a Style Tag

You can embed CSS rules directly into HTML documents by using a tag. Here’s what this looks like:

Similar to the link tag, the attribute can be omitted for HTML5, and the value controls when your styles are applied (leave it off to default to all devices).

Add your CSS rules between the opening and closing style tags and write your CSS the same way as you do in stand-alone stylesheet files.

CSS rules are render-blocking so it’s recommended to add style tags into the of the HTML document so they download as soon as possible. We’ll discuss render-blocking CSS shortly.

Advantages of embedded style tags

  • Faster loading times: Because the CSS is part of the HTML document, the whole page exists as just one file. No extra HTTP requests are required. I use this method on my responsive columns demo layouts so when people view the source of the page they can see the HTML and the CSS code together.
  • Works great with dynamic styles: If you’re using a database to generate page content you can also generate dynamic styles at the same time. Blogger does this by dynamically inserting the colors for headings and other elements into the CSS rules embedded in the page. This allows users to change these colors from an admin page without actually editing the CSS in their blog templates.

Disadvantages

Embedded styles must be downloaded with every page request: These styles cannot be cached by the browser and re-used for another page. Because of this, it’s recommended to embed a minimal amount of CSS as possible.

File Download Dialog Box

Sometimes it is desired that you want to give an option where a user will click a link and it will pop up a «File Download» box to the user instead of displaying actual content. This is very easy and can be achieved using an HTTP header in your HTTP response.

For example, if you want make a Filename file downloadable from a given link then its syntax will be as follows.

#!/usr/bin/perl

# Additional HTTP Header
print "Content-Type:application/octet-stream; name = \"FileName\"\r\n";
print "Content-Disposition:attachment; filename = \"FileName\"\r\n\n";

# Open the target file and list down its content as follows
open( FILE, "<FileName" );

while(read(FILE, $buffer, 100)){
   print("$buffer");
}

Note − For more detail on PERL CGI programs, go through tutorial PERL and CGI.

19 Lectures
2 hours

More Detail

Video

16 Lectures
1.5 hours

More Detail

Video

18 Lectures
1.5 hours

More Detail

Video

57 Lectures
5.5 hours

More Detail

Video

54 Lectures
6 hours

More Detail

Video

Vector Graphics with SVG & HTML — Complete course + projects

Things to remember

  • An import’s mimetype is .

  • Resources from other origins need to be CORS-enabled.

  • Imports from the same URL are retrieved and parsed once. That means script in an import is only executed the first time the import is seen.

  • Scripts in an import are processed in order, but do not block the main document parsing.

  • An import link doesn’t mean «#include the content here». It means «parser, go off an fetch this document so I can use it later». While scripts execute at import time, stylesheets, markup, and other resources need to be added to the main page explicitly. Note, don’t need to be added explicitly. This is a major difference between HTML Imports and , which says «load and render this content here».

5 последних уроков рубрики «HTML5»

  • В этом уроке я покажу процесс создания собственных HTML тегов. Пользовательские теги решают множество задач: HTML документы становятся проще, а строк кода становится меньше.

  • Сегодня мы посмотрим, как можно организовать проверку доступности атрибута HTML5 с помощью JavaScript. Проверять будем работу элементов details и summary.

  • HTML5 — глоток свежего воздуха в современном вебе. Она повлиял не только на классический веб, каким мы знаем его сейчас. HTML5 предоставляет разработчикам ряд API для создания и улучшения сайтов с ориентацией на мобильные устройства. В этой статье мы рассмотрим API для работы с вибрацией.

  • Веб дизайнеры частенько сталкиваются с необходимостью создания форм. Данная задача не простая, и может вызвать головную боль (особенно если вы делаете что-то не стандартное, к примеру, много-страничную форму). Для упрощения жизни можно воспользоваться фрэймворком. В этой статье я покажу вам несколько практических приёмов для создания форм с помощью фрэймворка Webix.

  • Знакомство с фрэймворком Webix

    В этой статье мы бы хотели познакомить вас с фрэймворком Webix. Для демонстрации возможностей данного инструмента мы создадим интерфейс online аудио плеера. Не обольщайтесь — это всего лишь модель интерфейса. Исходный код доступен в демо и на странице GitHub.

Атрибут href

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

Вот пример сложения двух атрибутов к элементу <a>(который используется для создания гиперссылки на другую веб — страницу).

Пример HTML:

Попробуй сам

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

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

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

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

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

Пример HTML:

Попробуй сам

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

Атрибут alt

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

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

Attributes

Attribute Value Description
crossorigin anonymoususe-credentials Specifies how the element handles cross-origin requests
href URL Specifies the location of the linked document
hreflang language_code Specifies the language of the text in the linked document
media media_query Specifies on what device the linked document will be displayed
referrerpolicy no-referrerno-referrer-when-downgradeorigin
origin-when-cross-originunsafe-url
Specifies which referrer to use when fetching the resource
rel alternate
author
dns-prefetchhelp
icon
license
next
pingbackpreconnect
prefetchpreloadprerender
prev
search
stylesheet
Required. Specifies the relationship between the current document and the linked document
sizes HeightxWidthany Specifies the size of the linked resource. Only for rel=»icon»
title   Defines a preferred or an alternate stylesheet
type media_type Specifies the media type of the linked document

HTML Tags

<!—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>

Connecting a CSS External Style Sheet to an HTML File

While there are multiple approaches linking CSS to an HTML file, the most efficient way is to link an external style sheet to an HTML document. It requires a separate document with a .css extension which solely contains all CSS rules without HTML tags.

Unlike internal and inline styles, this method changes many HTML pages by editing one CSS file. It saves time – there is no need to change each CSS property on every website’s HTML page. 

Start linking style sheets to HTML files by creating an external CSS document using an HTML text editor and adding CSS rules. For instance, here are the style rules of example.css

body {
  background-color: yellow;
}

h1 {
  color: blue;
  margin-right: 30px;
}

Make sure not to add a space between the property value. For example, instead of margin-right: 30px write margin-right: 30 px.

Then, use the <link> tag in the <head> section of your HTML page to link a CSS file to an HTML document. Next, specify the name of your external CSS file. In this case, it’s example.css so the code will look as follows:

<head>
<link rel="stylesheet" type="text/css" href="example.css" media=”screen” />
</head>

For better understanding, here’s a breakdown of the attributes contained within the <link> tag:

  • rel – defines the relationship between the linked document and the current one. Use the rel attribute only when the href attribute is present.
  • type – determines the content of the linked file or document between the <style> and </style> tags. It has a text or css as the default value.
  • href – specifies the location of the CSS file you want to link to the HTML. If both HTML and CSS files are in the same folder, enter only the file name. Otherwise, include the folder name in which you store the CSS file.
  • media – describes the type of media the CSS styles are optimized for. In this example, we put screen as the attribute value to imply its use for computer screens. To apply the CSS rules to printed pages, set the value to print.

Once you’ve included the <link> element in your HTML file, save the changes and enter your website’s URL in your web browser. Styles written in the CSS file should change the look of the website.

Although external CSS helps make the web development process easier, there are a few things to keep in mind that HTML pages might not be rendered properly before the external style sheet is loaded. Furthermore, linking to several CSS documents can increase your website’s loading time.

On that note, if you want to edit a specific HTML element, it might be better to use the inline style method. Meanwhile, the internal or embedded style might be ideal for applying CSS rules to a single page.

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

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

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

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

Рейтинг
( Пока оценок нет )
Editor
Editor/ автор статьи

Давно интересуюсь темой. Мне нравится писать о том, в чём разбираюсь.

Понравилась статья? Поделиться с друзьями:
Люкс-хост
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: