Artinblog logo
  • DLE
    • Шаблоны
    • Модули
  • SEO
    • SEO для начинающих
  • Общество
  • jQuery
  • Дизайн
  • Услуги
Главная » jQuery » Всплывающие подсказки при помощи jQuery qTip RSS
дек 25 2012 photo

Всплывающие подсказки при помощи jQuery qTip

admin 135 141
  • 80
  • 1
  • 2
  • 3
  • 4
  • 5

Всплывающие подсказки - jQuery qTip

 

Браузеры автоматически создают всплывающие подсказки, когда веб-мастера прописывают в атрибут title какой-либо текст (как правило, атрибут title применяется к тегам <a> и <img>, т.е. к ссылкам и изображениям). Когда пользователи наводят курсором мыши на теги, в которых присутствует атрибут title, то браузер отображает всплывающую подсказку. Именно такие всплывающие подсказки (tooltip) мы и будем редактировать.


В данной статье будет рассмотрено:

- как использовать плагин qTip для замены стандартных всплывающих подсказок
- как настроить qTip tooltips
- как создать навигационное меню при помощи qTip
- как отобразить Ajax контент во всплывающей подсказке

 

Простые пользовательские текстовые всплывающие подсказки


Надеюсь не нужно объяснять, что такие атрибуты как title, alt, часто бывают крайне необходимы. Ведь они помогают пользователям лучше ориентироваться в большом количестве информации и, к тому же, крайне полезны для поисковой оптимизации сайта. Единственная проблема с подсказками – они не могут быть изменены при помощи CSS стилей. Для решения этой проблемы задействуем возможности jQuery.

1. Создадим базовый каркас HTML файла, который содержит ссылки с атрибутом title.

<p>Перечень ссылок:</p>
<ul>
<li><a href="home.html" title="Заголовок домашней страницы">Главная</a></li>
<li><a href="about.html" title="Познакомьтесь лучше с нашей компанией">О компании</a></li>
<li><a href="contact.html" title="Отправьте нам сообщение!">Контакты</a></li>
<li><a href="work.html" title="Изучите наше портфолио">Портфолио</a></li>
</ul>



2. Теперь необходимо загрузить плагин qTip из GitHub репозитария.

3. Подключаем скаченные файлы:

<head>
<script src="jquery.js"></script>// Стандартная библиотека jQuery
<script src="jquery.qtip.min.js"></script>
<script src="scripts.js"></script>//В этом файле будем прописывать jQuery скрипты
<link rel="stylesheet" type="text/css" href="jquery.qtip.min.css">
</head>



4. Для работы всплывающей подсказки достаточно прописать в scripts.js:

$(document).ready(function(){
      $('a[title]').qtip();
});



Эта конструкция означает, что для всех ссылок, у которых присутствует атрибут title будет применен метод qtip().

Настройка jQuery qTip


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

 

Всплывающие подсказки при помощи jQuery qTip

 

$('a[title]').qtip({
   position: {
      my: 'bottom center', //Положение курсора
      at: 'top center', //Положение всплывающей подсказки
      viewport: $(window) //Подсказка не будет вылизать за края экрана
   }
});



2. После настройки позиции, можно заняться цветовой схемой отображения подсказки. По умолчанию в файле jquery.qtip.min.css содержатся следующие цветовые стили:

- qtip-default (желтый стиль по умолчанию)

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-light

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-dark

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-red

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-green

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-blue

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-youtube

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-jtools

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-cluetip

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-tipsy

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-tipped

 

 Всплывающие подсказки при помощи jQuery qTip

 

- qtip-bootstrap

 

 Всплывающие подсказки при помощи jQuery qTip


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

$('a[title]').qtip({
   position: {
      my: 'bottom center',
      at: 'top center',
      viewport: $(window)
   },
   style: {
      classes: 'qtip-green qtip-shadow'
   }
});

 

Создание навигационного меню с всплывающимися подсказками


1. Для начала создадим HTML каркас навигационного меню:

<ul id="navigation">
<li><a href="home.html" title="Главная страница">Home</a></li>
<li><a href="about.html" title="О компании">About</a></li>
<li><a href="contact.html" title="Обратная связь">Contact</a></li>
<li><a href="work.html" title="Наше портфолио">Our Work</a></li>
</ul>



2. Далее добавим некоторые CSS стили в styles.css и подключим нашу таблицу стилей:

#navigation {
   background: rgb(132,136,206); /* Old browsers */
   background: -moz-linear-gradient(top, rgba(132,136,206,1) 0%, rgba(72,79,181,1) 50%, rgba(132,136,206,1) 100%); /* FF3.6+ */
   background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(132,136,206,1)), color-stop(50%,rgba(72,79,181,1)), color-stop(100%,rgba(132,136,206,1))); /* Chrome,Safari4+ */
   background: -webkit-linear-gradient(top, rgba(132,136,206,1) 0%,rgba(72,79,181,1) 50%,rgba(132,136,206,1) 100%); /* 
Chrome10+,Safari5.1+ */
   background: -o-linear-gradient(top, rgba(132,136,206,1) 0%,rgba(72,79,181,1) 50%,rgba(132,136,206,1) 100%); /* Opera11.10+ 
*/
   background: -ms-linear-gradient(top, rgba(132,136,206,1) 0%,rgba(72,79,181,1) 50%,rgba(132,136,206,1) 100%); /* IE10+ */
   filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#8488ce', endColorstr='#8488ce',GradientType=0 ); 
/* IE6-9 */
   background: linear-gradient(top, rgba(132,136,206,1) 0%,rgba(72,79,181,1) 50%,rgba(132,136,206,1) 100%); /* W3C */
   list-style-type: none;
   margin: 100px 20px 20px 20px;
   padding: 0;
   overflow: hidden;
   -webkit-border-radius: 5px;
   -moz-border-radius: 5px;
   border-radius: 5px;
}
#navigation li  {
   margin: 0;
   padding: 0;
   display: block;
   float: left;
   border-right: 1px solid #4449a8;
}
#navigation a  {
   color: #fff;
   border-right: 1px solid #8488ce;
   display: block;
   padding: 10px;
}
#navigation a:hover {
   background: #859900;
   border-right-color: #a3bb00;
}

 

В результате должна получиться следующая картина:

 

Всплывающие подсказки при помощи jQuery qTip


3. В файл scripts.js добавим:

$('#navigation a').qtip({
   position: {
  my: 'top center',
  at: 'bottom center',
  viewport: $(window)
   },
   show: {
  effect: function(offset) {
 $(this).slideDown(300);
  }
   },
   hide: {
  effect: function(offset) {
 $(this).slideUp(100);
  }
   },
   style: {
  classes: 'qtip-green qtip-shadow',
   }
});

 

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

Отображение другого контента во всплывающей подсказке


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

1. Вначале создаем ссылку и присваиваем ей класс:

<a href="tooltip.txt" class="infobox" title="ToolTip">Эта ссылка берет контент из файла при помощи Ajax</a>



Значение атрибута href=”tooltip.txt” означает, что гиперссылка ссылается на обычный txt файл.

2. Далее добавим в scripts.js следующее:

$('.infobox').each(function(){
      $(this).qtip({
         content: {
            text: 'Загрузка...', //Пока грузится контент, будет отображаться эта запись
            ajax: {
               url: $(this).attr('href') //Откуда брать контент
            },
         title: { //Добавляет поле с заголовком в tooltip
            text: $(this).attr('title'),
            button: true //Добавляет кнопку для закрытия подсказки
         }
         },
         position: {
            my: 'top center',
            at: 'bottom center',
            effect: false, //Убирает выезжающий эффект
            viewport: $(window)
         },
         show: {
            event: 'click', //Подсказка отобразиться при нажатии на ссылку, можно заменить на ‘hover’, тогда подсказка отобразиться при наведении
            solo: true //Позволяет отобразить только один tooltip на экране
         },
         hide: 'unfocus', //Подсказка закроется при клике по другому элементу страницы
         style: {
            classes: 'qtip-green qtip-shadow'
         }
      });
    }).bind('click', function(e){e.preventDefault()}); //При нажатии на ссылку браузер не будет загружать url

 

Данный Ajax прием работает только при запущенном сервере. Чтобы он заработал на локальном компьютере необходимо установить, к примеру, Denwer.

 

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

 

Демо qTip.rar [42,04 Kb] (cкачиваний: 435)

Теги: jQuery qTip tooltip всплывающие подсказки

HashFlare
Другие новости по теме:
  • Как закрыть ссылку от индексации при помощи javascript
  • Всплывающее окно jquery на сайте
  • 10 новых jQuery плагинов 2014 года
  • Красивое вертикальное меню на CSS
  • Горизонтальное меню на CSS

Комментарии к: Всплывающие подсказки при помощи jQuery qTip (130)

    1. №91  Гость MadieHarvey 18-01-2022 Цитировать
      Hi there, just wanted to say, I enjoyed this blog post. It was funny. Keep on posting!
    1. №92  Гость LeonelNdz221659 22-01-2022 Цитировать
      Searching online is a great way of checking out a company and what they can offer you. After ensuring that the collar is flat against the base, it is a simple task to apply roof sealant to the base and around the pipe to form a tight seal. Defend your dwelling by keeping the roof in very good restore.
    1. №93  Гость MadieHarvey 22-01-2022 Цитировать
      Hello There. I found your blog using msn. This is an extremely well written article. I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I'll certainly comeback.
    1. №94  Гость MadieHarvey 23-01-2022 Цитировать
      Good day I am so happy I found your website, I really found you by accident, while I was browsing on Google for something else, Anyways I am here now and would just like to say thank you for a marvelous post and a all round entertaining blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the awesome b.
    1. №95  Гость LeonelNdz221659 23-01-2022 Цитировать
      Green rooftops also help roofs last longer by adding a layer of protection between the rooftop and the wear-and-tear of the sun, wind, and rain. Unlike what quite a few perceive, getting a solar vent is now way less costly as significant sellers and merchants like Solar Royal have a 30% federal tax credit on their renewable power know-how appliance. Most roofers in Maine also do gutter installations.
    1. №96  Гость MadieHarvey 23-01-2022 Цитировать
      I couldn't refrain from commenting. Well written!
    1. №97  Гость MadieHarvey 24-01-2022 Цитировать
      Hmm is anyone else having problems with the pictures on this blog loading? I'm trying to determine if its a problem on my end or if it's the blog. Any feedback would be greatly appreciated.
    1. №98  Гость MadieHarvey 24-01-2022 Цитировать
      Howdy very nice web site!! Guy .. Excellent .. Amazing .. I'll bookmark your site and take the feeds additionally? I'm satisfied to search out so many helpful information here in the put up, we'd like work out extra techniques in this regard, thank you for sharing. . . . . .
    1. №99  Гость LeonelNdz221659 24-01-2022 Цитировать
      With honeycomb construction and double-pane glass you get style and quality, guaranteed. After ensuring that the collar is flat against the base, it is a simple task to apply roof sealant to the base and around the pipe to form a tight seal. The stress factor is relieved from you, as your decision will be only to determine which the most favorable estimate for your needs.
    1. №100  Гость MadieHarvey 25-01-2022 Цитировать
      Greetings! Very useful advice within this article! It's the little changes which will make the largest changes. Thanks a lot for sharing!
    1. №101  Гость MadieHarvey 25-01-2022 Цитировать
      It's an remarkable article in favor of all the web viewers; they will get advantage from it I am sure.
    1. №102  Гость MadieHarvey 26-01-2022 Цитировать
      I do accept as true with all of the ideas you have presented on your post. They are really convincing and can definitely work. Still, the posts are too brief for newbies. Could you please lengthen them a bit from next time? Thanks for the post.
    1. №103  Гость LeonelNdz221659 27-01-2022 Цитировать
      With honeycomb construction and double-pane glass you get style and quality, guaranteed. This is not a pleasant situation to be in, but the reality is that you simply have to choice. through the pre-punched holes to secure the shingle in place.
    1. №104  Гость MadieHarvey 27-01-2022 Цитировать
      Fantastic beat ! I would like to apprentice whilst you amend your web site, how could i subscribe for a weblog website? The account aided me a acceptable deal. I have been tiny bit familiar of this your broadcast offered brilliant clear idea
    1. №105  Гость MadieHarvey 27-01-2022 Цитировать
      Please let me know if you're looking for a article writer for your site. You have some really great articles and I believe I would be a good asset. If you ever want to take some of the load off, I'd love to write some articles for your blog in exchange for a link back to mine. Please send me an email if interested. Cheers!
    1. №106  Гость LeonelNdz221659 28-01-2022 Цитировать
      With honeycomb construction and double-pane glass you get style and quality, guaranteed. Bath roofing services, roof repair Bath, Avon & Somerset. The stress factor is relieved from you, as your decision will be only to determine which the most favorable estimate for your needs.
    1. №107  Гость LeonelNdz221659 29-01-2022 Цитировать
      Green rooftops also help roofs last longer by adding a layer of protection between the rooftop and the wear-and-tear of the sun, wind, and rain. If the cracks are too large, you will need to replace the flashing and anything else that is involved, such as grommets or moldings. Though, with the right tools, it can provide great benefits getting through roofing projects.
    1. №108  Гость MadieHarvey 30-01-2022 Цитировать
      Helpful info. Fortunate me I discovered your web site by chance, and I am surprised why this accident did not came about earlier! I bookmarked it.
    1. №109  Гость LeonelNdz221659 30-01-2022 Цитировать
      The roof is one of the most important safety features for the stability of a home during unfavorable weather. This can be done by ensuring that the ground near the house is leveled or banked to reduce the chances of puddles of water that form when it rains. When trying to find a good professional contractor to do your roofing work, you would be wise to ask any potential company for references.
    1. №110  Гость LeonelNdz221659 30-01-2022 Цитировать
      Green rooftops also help roofs last longer by adding a layer of protection between the rooftop and the wear-and-tear of the sun, wind, and rain. Check if the Denver roof repair company is a member of BBB or not. Most roofers in Maine also do gutter installations.
    1. №111  Гость MadieHarvey 31-01-2022 Цитировать
      When I initially left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and now whenever a comment is added I get 4 emails with the exact same comment. Perhaps there is a means you are able to remove me from that service? Cheers!
    1. №112  Гость LeonelNdz221659 31-01-2022 Цитировать
      If doing this roof job on your own is too hard it might be worth it to call in a professional repair team who is prepared to bring in all the tools you need and the honed expertise in completing the repair for you. Repairing leaking roofs is one of the most common DIY activities. through the pre-punched holes to secure the shingle in place.
    1. №113  Гость MadieHarvey 31-01-2022 Цитировать
      I like reading a post that will make men and women think. Also, thanks for allowing me to comment!
    1. №114  Гость LeonelNdz221659 02-02-2022 Цитировать
      If doing this roof job on your own is too hard it might be worth it to call in a professional repair team who is prepared to bring in all the tools you need and the honed expertise in completing the repair for you. This can be done by ensuring that the ground near the house is leveled or banked to reduce the chances of puddles of water that form when it rains. Defend your dwelling by keeping the roof in very good restore.
    1. №115  Гость MadieHarvey 02-02-2022 Цитировать
      Pretty! This was a really wonderful article. Thanks for supplying these details.
    1. №116  Гость MadieHarvey 03-02-2022 Цитировать
      I'm really impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you customize it yourself? Either way keep up the nice quality writing, it's rare to see a nice blog like this one nowadays.
    1. №117  Гость MadieHarvey 04-02-2022 Цитировать
      Hello all, here every one is sharing these kinds of familiarity, thus it's good to read this webpage, and I used to visit this website every day.
    1. №118  Гость LeonelNdz221659 04-02-2022 Цитировать
      If doing this roof job on your own is too hard it might be worth it to call in a professional repair team who is prepared to bring in all the tools you need and the honed expertise in completing the repair for you. This is not a pleasant situation to be in, but the reality is that you simply have to choice. Though, with the right tools, it can provide great benefits getting through roofing projects.
    1. №119  Гость MadieHarvey 04-02-2022 Цитировать
      Wow that was odd. I just wrote an extremely long comment but after I clicked submit my comment didn't show up. Grrrr... well I'm not writing all that over again. Anyway, just wanted to say superb blog!
    1. №120  Гость LeonelNdz221659 05-02-2022 Цитировать
      Ask about the procedures they do when working on a roof Vancouver homes have. It's even Energy Star compliant which easily will save you a great deal of money, and the reflective characteristic of TPO can conserve hundreds of thousands of dollars for business by cutting back the amount of energy utilized for cooling. The stress factor is relieved from you, as your decision will be only to determine which the most favorable estimate for your needs.
1 2 3 4 5
Имя:*
Комментарий:
Сервис не доступен
Похожие статьи:
  • Как закрыть ссылку от индексации при помощи javascript
  • Всплывающее окно jquery на сайте
  • 10 новых jQuery плагинов 2014 года
  • Красивое вертикальное меню на CSS
  • Горизонтальное меню на CSS
  • Популярное
  • Авторизация
Войти
Забыли? Регистрация
HashFlare
  • Обратная связь
  • Карта сайта
При копировании материалов ссылка на источник Artinblog.ru обязательна. Copyright © 2012 - 2015