Что такое jquery tabs

Обновлено: 05.07.2024

Для создания виджета Tabs используется метод tabs(). Как и в случае виджета Accordion, для применения этого метода потребуется отдельная структура HTML-элементов. Пример такой структуры приведен ниже:

Элемент, к которому вы собираетесь применить метод tabs(), должен содержать элементы двух типов. Элементы первого типа — это элементы содержимого, т.е. элементы, содержимое которых должно отображаться в отдельных вкладках. Ко второму типу относятся структурные элементы, содержащие информацию, которая используется для создания структуры вкладок.

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

Очень важно, чтобы каждый элемент содержимого был снабжен идентификатором (атрибутом id) и виджет мог находить элемент, который требуется отобразить. Для создания необходимой структуры используются элементы <li>, каждый из которых должен содержать элемент <a>:

Количество элементов <li> определяет количество вкладок. Содержимое элемента <a> используется в качестве ярлыка вкладки, а атрибут href указывает, к какому именно элементу содержимого (вкладке) относится данный ярлык.

Каким образом использованная в примере структура HTML-элементов отображается в окне браузера, показано на рисунке:

Создание вкладок Tabs jQuery UI

Вкладки являются хорошо известной метафорой интерфейса пользователя. Щелчок на вкладке приводит к отображению соответствующего элемента содержимого. Как и виджет Accordion с его структурой панелей, напоминающей клавиатуру аккордеона и раздвигающейся подобно мехам гармошки, виджет Tabs обеспечивает возможность относительно компактного представления больших объемов содержимого, что позволяет сконцентрировать внимание на наиболее важной информации.

Это означает, что необходимо тщательно продумывать, каким образом вкладки и их содержимое должны соотноситься между собой. Ваша задача состоит в том, чтобы путем группирования информации избавить пользователя от необходимости часто переходить с одной вкладки на другую для получения доступа к нужным данным. Как и в случае любого пользовательского интерфейса, это требует глубокого понимания задач, решаемых пользователем, и того, как организован весь его рабочий процесс (а не только ваша система).

QuickNavExamples

Options

Methods

Extension Points

Events

Tabs are generally used to break content into multiple sections that can be swapped to save space, much like an accordion.

Tabs have a particular set of markup that must be used in order for them to work properly:

  • The tabs themselves must be in either an ordered ( <ol> ) or unordered ( <ul> ) list
  • Each tab "title" must be inside of a list item ( <li> ) and wrapped by an anchor ( <a> ) with an href attribute
  • Each tab panel may be any valid element but it must have an id which corresponds to the hash in the anchor of the associated tab.

The content for each tab panel can be defined in-page or can be loaded via Ajax; both are handled automatically based on the href of the anchor associated with the tab. By default tabs are activated on click, but the events can be changed to hover via the event option.

Below is some sample markup:

Keyboard interaction

When focus is on a tab, the following key commands are available:

  • UP / LEFT : Move focus to the previous tab. If on first tab, moves focus to last tab. Activate focused tab after a short delay.
  • DOWN / RIGHT : Move focus to the next tab. If on last tab, moves focus to first tab. Activate focused tab after a short delay.
  • CTRL + UP / LEFT : Move focus to the previous tab. If on first tab, moves focus to last tab. The focused tab must be manually activated.
  • CTRL + DOWN / RIGHT : Move focus to the next tab. If on last tab, moves focus to first tab. The focused tab must be manually activated.
  • HOME : Move focus to the first tab. Activate focused tab after a short delay.
  • END : Move focus to the last tab. Activate focused tab after a short delay.
  • CTRL + HOME : Move focus to the first tab. The focused tab must be manually activated.
  • CTRL + END : Move focus to the last tab. The focused tab must be manually activated.
  • SPACE : Activate panel associated with focused tab.
  • ENTER : Activate or toggle panel associated with focused tab.
  • ALT / OPTION + PAGE UP : Move focus to the previous tab and immediately activate.
  • ALT / OPTION + PAGE DOWN : Move focus to the next tab and immediately activate.

When focus is in a panel, the following key commands are available:

  • CTRL + UP : Move focus to associated tab.
  • ALT / OPTION + PAGE UP : Move focus to the previous tab and immediately activate.
  • ALT / OPTION + PAGE DOWN : Move focus to the next tab and immediately activate.

Theming

The tabs widget uses the jQuery UI CSS framework to style its look and feel. If tabs specific styling is needed, the following CSS class names can be used for overrides or as keys for the classes option:

  • ui-tabs : The outer container of the tabs. This element will additionally have a class of ui-tabs-collapsible when the collapsible option is set.
    • ui-tabs-nav : The list of tabs.
      • ui-tabs-tab : One of the items in the list of tabs.The active item will have the ui-tabs-active class. Any list item whose associated content is loading via an Ajax call will have the ui-tabs-loading class.
        • ui-tabs-anchor : The anchors used to switch panels.

        Dependencies

        Additional Notes:

        • This widget requires some functional CSS, otherwise it won't work. If you build a custom theme, use the widget's specific CSS file as a starting point.

        Methods

        abort() Returns: jQuery (plugin only)

        Terminate all running tab ajax requests and animations.

        Invoke the abort method:

        add( url, label [, index ] ) Returns: jQuery (plugin only)

        Where to add the new tab (zero-based). If omitted, the new tab will be added as the last tab.

        Invoke the add method:

        destroy() Returns: jQuery (plugin only)

        Removes the tabs functionality completely. This will return the element back to its pre-init state.

        Invoke the destroy method:

        disable() Returns: jQuery (plugin only)

        Invoke the method:

        disable( index ) Returns: jQuery (plugin only)

        Invoke the method:

        enable() Returns: jQuery (plugin only)

        Invoke the method:

        enable( index ) Returns: jQuery (plugin only)

        Invoke the method:

        length() Returns: Integer

        Retrieve the number of tabs of the first matched tab pane.

        Invoke the length method:

        load( index ) Returns: jQuery (plugin only)

        Invoke the load method:

        option( optionName ) Returns: Object

        Gets the value currently associated with the specified optionName .

        Invoke the method:

        option() Returns: PlainObject

        Gets an object containing key/value pairs representing the current tabs options hash.

        Invoke the method:

        option( optionName, value ) Returns: jQuery (plugin only)

        Sets the value of the tabs option associated with the specified optionName .

        Invoke the method:

        option( options ) Returns: jQuery (plugin only)

        Invoke the method:

        remove( index ) Returns: jQuery (plugin only)

        Invoke the remove method:

        rotate( duration [, continuing ] ) Returns: jQuery (plugin only)

        The duration in milliseconds for each tab to be visible before rotating to the next tab. Whether or not to continue the rotation after a tab has been selected by a user.

        Invoke the rotate method:

        select( index ) Returns: jQuery (plugin only)

        Invoke the select method:

        url( index, url ) Returns: jQuery (plugin only)

        Change the URL from whcih an Ajax (remote) tab will be loaded. The specified URL will be used for subsequent loads. Note that you can not only change the URL for an existing remote tab with this method, but also turn an in-page tab into a remote tab.

        Invoke the url method:

        widget() Returns: jQuery

        Returns a jQuery object containing the tabs container.

        Invoke the widget method:

        Получение содержимого вкладок с помощью Ajax

        Одной из замечательных особенностей вкладок jQuery UI является возможность получения содержимого с помощью Ajax. Для этого достаточно указать URL-адрес источника в атрибуте href соответствующего элемента. Чтобы продемонстрировать, как это работает, я создал документ под названием tabflowers.html, содержимое которого представлено в примере ниже:

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

        Вместо того чтобы использовать настройки метода tabs(), вы изменяете структуру элемента. В данном примере я добавил новую вкладку, назвав ее "Содержимое Ajax", и указал URL-адрес источника содержимого, которое должно быть загружено. Результат представлен на рисунке:

        Получение содержимого вкладки посредством Ajax

        По умолчанию загружаться во вкладки с помощью Ajax могут только HTML-документы, однако, как будет показано в одном из следующих разделов, для этого пригодны также данные в формате JSON.

        Tabs Widget

        Description: A single content area with multiple panels, each associated with a header in a list.

        Methods

        destroy() Returns: jQuery (plugin only)

        Removes the tabs functionality completely. This will return the element back to its pre-init state.

        Invoke the destroy method:

        disable() Returns: jQuery (plugin only)

        Invoke the method:

        disable( index ) Returns: jQuery (plugin only)

        Invoke the method:

        disable( href ) Returns: jQuery (plugin only)

        Disables a tab. The selected tab cannot be disabled.

        Invoke the method:

        enable() Returns: jQuery (plugin only)

        Invoke the method:

        enable( index ) Returns: jQuery (plugin only)

        Invoke the method:

        enable( href ) Returns: jQuery (plugin only)

        Invoke the method:

        instance() Returns: Object

        Retrieves the tabs's instance object. If the element does not have an associated instance, undefined is returned.

        Unlike other widget methods, instance() is safe to call on any element after the tabs plugin has loaded.

        Invoke the instance method:

        load( index ) Returns: jQuery (plugin only)

        Invoke the method:

        load( href ) Returns: jQuery (plugin only)

        Invoke the method:

        option( optionName ) Returns: Object

        Gets the value currently associated with the specified optionName .

        Note: For options that have objects as their value, you can get the value of a specific key by using dot notation. For example, "foo.bar" would get the value of the bar property on the foo option.

        Invoke the method:

        option() Returns: PlainObject

        Gets an object containing key/value pairs representing the current tabs options hash.

        Invoke the method:

        option( optionName, value ) Returns: jQuery (plugin only)

        Sets the value of the tabs option associated with the specified optionName .

        Note: For options that have objects as their value, you can set the value of just one property by using dot notation for optionName . For example, "foo.bar" would update only the bar property of the foo option.

        Invoke the method:

        option( options ) Returns: jQuery (plugin only)

        Invoke the method:

        refresh() Returns: jQuery (plugin only)

        Process any tabs that were added or removed directly in the DOM and recompute the height of the tab panels. Results depend on the content and the heightStyle option.

        Invoke the refresh method:

        widget() Returns: jQuery

        Returns a jQuery object containing the tabs container.

        Invoke the widget method:

        Events

        add( event, ui ) Type: tabsadd

        Initialize the tabs with the add callback specified:

        Bind an event listener to the tabsadd event:

        create( event, ui ) Type: tabscreate

        Note: The ui object is empty but included for consistency with other events.

        Initialize the tabs with the create callback specified:

        Bind an event listener to the tabscreate event:

        disable( event, ui ) Type: tabsdisable

        Initialize the tabs with the disable callback specified:

        Bind an event listener to the tabsdisable event:

        enable( event, ui ) Type: tabsenable

        Initialize the tabs with the enable callback specified:

        Bind an event listener to the tabsenable event:

        load( event, ui ) Type: tabsload

        The panel which was just populated by the Ajax response.

        Initialize the tabs with the load callback specified:

        Bind an event listener to the tabsload event:

        remove( event, ui ) Type: tabsremove

        Initialize the tabs with the remove callback specified:

        Bind an event listener to the tabsremove event:

        select( event, ui ) Type: tabsselect

        Triggered directly after a tab is selected. Can be canceled to prevent the tab from being selected.

        Initialize the tabs with the select callback specified:

        Bind an event listener to the tabsselect event:

        show( event, ui ) Type: tabsshow

        Triggered after a tab has been selected (after animation completes).

        Initialize the tabs with the show callback specified:

        Bind an event listener to the tabsshow event:

        Example:

        A simple jQuery UI Tabs

        jQuery UI 1.8

        Other Versions

        Books

        Copyright 2021 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath

        Tabs Widget

        Description: A single content area with multiple panels, each associated with a header in a list.

        Options

        Additional Ajax options to consider when loading tab content (see jQuery.ajax() ). Whether or not to cache remote tabs content, e.g., load only once or with every click. Cached content is being lazy loaded, e.g., once and only once for the first click. Note that to prevent the actual Ajax requests from being cached by the browser you need to provide an extra cache: false flag in the ajaxOptions option.
        • Boolean: Enable or disable all tabs.
        • Array: An array containing the zero-based indexes of the tabs that should be disabled, e.g., [ 0, 2 ] would disable the first and third tab.
        The type of event that the tabs should react to in order to activate the tab. To activate on hover, use "mouseover" . Enable animations for hidniga nd showing tab panels.
        • Object: Key/value pairs of properties to animate and optional duration, e.g., < height: "toggle", duration: 200 >.
        • Array: Animation settings in the form [ hideSettings, showSettings ] .
        If the remote tab, its anchor element that is, has no title attribute to generate an id from, an id/fragment identifier is created from this prefix and a unique id, for example "ui-tabs-54" . HTML template from which a new tab panel is created in case of adding a tab with the add() method or when creating a panel for a remote tab on the fly. The zero-based index of the panel that is selected (open). Setting selected to -1 will collapse all panels. This requires the collapsible option to be true . The HTML content to show in a tab title while remote content is loading. Set this option to an empty string to deactivate the spinner behavior. A span element must be present in the anchor tag of the title for the spinner content to be visible.

        Options

        • Boolean: Setting active to false will collapse all panels. This requires the collapsible option to be true .
        • Integer: The zero-based index of the panel that is active (open). A negative value selects panels going backward from the last panel.

        Initialize the tabs with the active option specified:

        Get or set the active option, after initialization:

        Specify additional classes to add to the widget's elements. Any of classes specified in the Theming section can be used as keys to override their value. To learn more about this option, check out the learn article about the classes option.

        Initialize the tabs with the classes option specified, changing the theming for the ui-tabs class:

        Get or set a property of the classes option, after initialization, here reading and changing the theming for the ui-tabs class:

        Initialize the tabs with the collapsible option specified:

        Get or set the collapsible option, after initialization:

        • Boolean: Enable or disable all tabs.
        • Array: An array containing the zero-based indexes of the tabs that should be disabled, e.g., [ 0, 2 ] would disable the first and third tab.

        Initialize the tabs with the disabled option specified:

        Get or set the disabled option, after initialization:

        The type of event that the tabs should react to in order to activate the tab. To activate on hover, use "mouseover" .

        Initialize the tabs with the event option specified:

        Get or set the event option, after initialization:

        • "auto" : All panels will be set to the height of the tallest panel.
        • "fill" : Expand to the available height based on the tabs' parent height.
        • "content" : Each panel will be only as tall as its content.

        Initialize the tabs with the heightStyle option specified:

        Get or set the heightStyle option, after initialization:

        • Boolean: When set to false , no animation will be used and the panel will be hidden immediately. When set to true , the panel will fade out with the default duration and the default easing.
        • Number: The panel will fade out with the specified duration and the default easing.
        • String: The panel will be hidden using the specified effect. The value can either be the name of a built-in jQuery animation method, such as "slideUp" , or the name of a jQuery UI effect, such as "fold" . In either case the effect will be used with the default duration and the default easing.
        • Object: If the value is an object, then effect , delay , duration , and easing properties may be provided. If the effect property contains the name of a jQuery method, then that method will be used; otherwise it is assumed to be the name of a jQuery UI effect. When using a jQuery UI effect that supports additional settings, you may include those settings in the object and they will be passed to the effect. If duration or easing is omitted, then the default values will be used. If effect is omitted, then "fadeOut" will be used. If delay is omitted, then no delay is used.

        Initialize the tabs with the hide option specified:

        Get or set the hide option, after initialization:

        • Boolean: When set to false , no animation will be used and the panel will be shown immediately. When set to true , the panel will fade in with the default duration and the default easing.
        • Number: The panel will fade in with the specified duration and the default easing.
        • String: The panel will be shown using the specified effect. The value can either be the name of a built-in jQuery animation method, such as "slideDown" , or the name of a jQuery UI effect, such as "fold" . In either case the effect will be used with the default duration and the default easing.
        • Object: If the value is an object, then effect , delay , duration , and easing properties may be provided. If the effect property contains the name of a jQuery method, then that method will be used; otherwise it is assumed to be the name of a jQuery UI effect. When using a jQuery UI effect that supports additional settings, you may include those settings in the object and they will be passed to the effect. If duration or easing is omitted, then the default values will be used. If effect is omitted, then "fadeIn" will be used. If delay is omitted, then no delay is used.

        Initialize the tabs with the show option specified:

        Get or set the show option, after initialization:

        Настройка виджета Tabs

        На первый взгляд, вкладки виджета Tabs могут показаться простой разновидностью панелей виджета Accordion, характеризующихся вертикальным расположением. Действительно, у этих виджетов есть общие характеристики, но для вкладок Tabs (далее просто вкладки) предусмотрено намного больше настраиваемых свойств и конфигурационных параметров.

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

        Свойства виджета Tabs
        Свойство Описание
        active Позволяет получить или задать индекс активной вкладки
        collapsible Если эта опция равна true, то пользователь не будет иметь возможности оставить невыбранными все вкладки. Значение по умолчанию — false, которое означает, что одна из вкладок всегда должна быть активна (открыта)
        disabled Установка значения true или false означает соответственно отключение или включение функциональности вкладок. Если в качестве значения задан массив чисел, то они указывают индексы отключаемых вкладок
        event Позволяет получить или задать событие, которое делает вкладку активной. По умолчанию таким событием является click, т.е. вкладка активизируется после выполнения на ней щелчка
        heightStyle Определяет высоту вкладок. Возможные значения: auto (высота всех вкладок будет одинаковой и равной высоте самой высокой вкладки), content (высота вкладки определяется ее содержимым), fill (вкладки занимают все пространство своего родительского элемента по высоте)
        show и hide Определяет эффекты, которые должны использоваться при анимации процессов открытия и закрытия вкладок. Значение по умолчанию — null, означающее, что эффекты не используются

        Методы, поддерживаемые виджетом jQuery UI Tabs, перечислены в таблице ниже. Использование наиболее полезных из них будет продемонстрировано в следующих разделах:

        Методы виджета Tabs
        Метод Описание
        tabs("destroy") Полностью удаляет функциональность виджета Tabs из базового HTML-элемента
        tabs("disable") Приостанавливает работу всего виджета или отдельных вкладок
        tabs("enable") Возобновляет работу ранее приостановленного виджета или отдельных вкладок
        tabs("option") Позволяет изменить одну или несколько опций. Более подробное описание настройки конфигурационных параметров виджетов jQuery UI на примере виджета Button описывались ранее
        tabs("load") Осуществляет принудительную загрузку содержимого вкладки
        tabs("refresh") Заставляет явно обновить внешний вид вкладок (удобно при программном изменении вкладок, например при их добавлении или удалении). Этот метод не принимает аргументов
        tabs("widget") Возвращает объект jQuery, представляющий виджет Tabs. Этот метод не принимает аргументов

        Отключение отдельных вкладок

        Если опции disable присвоено логическое значение, то оно воздействует на виджет Tabs в целом. Однако имеется возможность включать и отключать отдельные вкладки, указывая их номера в виде целочисленного массива, как показано в примере ниже:

        В этом документе мы создаем виджет Tabs со статическим содержимым и добавляем набор флажков, преобразуя их в кнопки-переключатели jQuery UI. Щелчок на кнопке приводит к включению или отключению соответствующей вкладки. Кроме того, мы используем событие select для отключения кнопки, когда соответствующая ей вкладка становится активной. Результат представлен на рисунке:

        Отключение и включение вкладок с помощью щелчков на кнопках

        Изменение типа события, активизирующего вкладку

        По умолчанию виджет Tabs реагирует на событие click. Это означает, что для активизации вкладки пользователь должен выполнить щелчок на ней. Опция event позволяет указать другое событие, наступление которого будет приводить к активизации вкладки. Чаще всего в этой роли выступают другие события мыши, как показано в примере ниже:

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

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

        Использование свертываемых вкладок

        Используя опцию collapsible, можно создать своего рода гибрид вкладок виджета Tabs и панелей виджета Accordion, как показано в примере ниже:

        Если опция collapsible равна true, то щелчок на активной вкладке приводит к ее свертыванию, точно так же, как в случае панели виджета Accordion. Я привел пример использования этой опции лишь для полноты обсуждения, но сам никогда не использую ее в своих проектах, поскольку считаю, что этот эффект не относится к числу интуитивно понятных для пользователей и лишь создает помехи в работе.

        Добавление и удаление вкладок

        Для добавления и удаления вкладок программным путем нужно использовать возможности jQuery и вызвать метод refresh для обновления виджета Tabs. Это может быть полезным при обработке динамического содержимого или при генерации вкладок в ответ на пользовательский ввод. Ниже показан соответствующий пример:

        В этом примере добавлены элемент input и два элемента button, позволяющие добавлять новые вкладки и удалять существующие. Эти дополнения документа отображены на рисунке:

        Включение в документ новых элементов, обеспечивающих добавление и удаление вкладок

        Когда на кнопке "Удалить активную вкладку" выполняется щелчок, мы получаем индекс активной вкладки с помощью опции active и удаляем соответствующий элемент <li> с помощью jQuery.

        Extension Points

        The tabs widget is built with the widget factory and can be extended. When extending widgets, you have the ability to override or add to the behavior of existing methods. The following methods are provided as extension points with the same API stability as the plugin methods listed above. For more information on widget extensions, see Extending Widgets with the Widget Factory.

        _getList() Returns: jQuery

        Determine which list should be converted to tabs. By default the first descendant list is used.

        Use the list with the class my-tabs or fall back to the default implementation.

        QuickNavExamples

        Options

        Methods

        Events

        Tabs are generally used to break content into multiple sections that can be swapped to save space, much like an accordion.

        The content for each tab panel can be defined in-page or can be loaded via Ajax; both are handled automatically based on the href of the anchor associated with the tab. By default tabs are activated on click, but the events can be changed to hover via the event option.

        Additional Notes:

        • This widget requires some functional CSS, otherwise it won't work. If you build a custom theme, use the widget's specific CSS file as a starting point.

        Делаем простые и легкие вкладки (tabs) на jQuery без наворотов

        В одном из проектов понадобилось использовать горизонтальные текстовые вкладки, хотел найти что-то готовое, но подключать bootstrap ради такого дела — это извращение нелогично. Попробовал найти простые jQuery плагины для вкладок, однако нашел только множество плагинов с кучей настроек, эффектами анимации и прочим. Было найдено пару вариантов «без выкрутасов», написанных на скорую руку, однако где-то было ограничение по количеству вкладок. В общем, меня ни один вариант не устроил. Как результат, в течении 15 минут родился несложный jQuery плагин, удовлетворяющий моим запросам. Решил поделиться, думаю, кому-нибудь да пригодится.

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

        Сам код плагина:

        Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.

        О песочнице

        Это «Песочница» — раздел, в который попадают дебютные посты пользователей, желающих стать полноправными участниками сообщества.

        Если у вас есть приглашение, отправьте его автору понравившейся публикации — тогда её смогут прочитать и обсудить все остальные пользователи Хабра.

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

        Читайте также: