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

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

admin 134 607
  • 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качиваний: 434)

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

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

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

    1. №1  Odisssey300 19-01-2013 Цитировать
      Что-то демо версия не хочет работать, а плагин интересный, пожалуй надо попробовать.
    1. №2  admin 19-01-2013 Цитировать
      Цитата: Odisssey300
      Что-то демо не хочет работать, а плагин интересный, пожалуй надо попробовать.

      Демо версию поправил. Проблема возникла из-за того, что я подключил стандартную jquery библиотеку из интернет репозитария сайта jquery.com по этой ссылке: "http://code.jquery.com/jquery-latest.min.js". Недавно библиотека обновилась до версии 1.9.0 и плагин qTip перестал работать. Следовательно могу предположить, что для корректной работы плагина необходима версия jquery 1.8+, либо надо ждать обновления qTip.
    1. №3  Yvette 26-12-2018 Цитировать
      cheap wigs36591 Troy
    1. №4  Maira 06-02-2019 Цитировать
      cheap jerseys cheap nfl jerseys fyhcdd7934
    1. №5  Julianne 08-02-2019 Цитировать
      wholesale nfl jerseys from china wholesale jerseys from china hycsss85279
    1. №6  Kristine 17-07-2019 Цитировать
      Clip In extensions
    1. №7  Mark 06-01-2020 Цитировать
      Over Thee Counter Viagra cheap cialis generic viagra for sale nizagara 100 mg vs visgra viagra on line Related Posts: generic viagra viagra without a doctor prescription amazon female viagra walmart cialis vs viagra
    1. №8  Sofia 21-01-2020 Цитировать
      travel backpack anti theft USB charging backpack grsmbp8642
    1. №9  Гость FloreneBolick34 14-12-2020 Цитировать
      Neat blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog jump out. Please let me know where you got your design. Thanks
    1. №10  Гость FloreneBolick34 16-12-2020 Цитировать
      magnificent points altogether, you simply won a brand new reader. What would you recommend in regards to your submit that you simply made a few days ago? Any positive?
    1. №11  Гость FloreneBolick34 16-12-2020 Цитировать
      I read this paragraph fully concerning the comparison of most recent and preceding technologies, it's amazing article.
    1. №12  Гость FloreneBolick34 18-12-2020 Цитировать
      Appreciate the recommendation. Let me try it out.

      I am really impressed along with your writing abilities and also with the layout for your weblog. Is that this a paid subject matter or did you customize it yourself? Anyway keep up the excellent quality writing, it's rare to see a nice weblog like this one these days..
    1. №13  Гость FloreneBolick34 18-12-2020 Цитировать
      You actually make it seem really easy together with your presentation but I to find this matter to be actually something that I believe I might never understand. It sort of feels too complex and very extensive for me. I am having a look ahead for your next publish, I'll try to get the grasp of it!
    1. №14  Гость FloreneBolick34 18-12-2020 Цитировать
      Undeniably believe that which you said. Your favorite reason appeared to be on the web the easiest thing to be aware of. I say to you, I certainly get annoyed while people think about worries that they just don't know about. You managed to hit the nail upon the top and also defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks
    1. №15  Гость MadieHarvey 20-12-2020 Цитировать
      Hi, just wanted to say, I enjoyed this post. It was helpful. Keep on posting!
    1. №16  Гость MadieHarvey 20-12-2020 Цитировать
      Howdy! I'm at work browsing your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the excellent work!
    1. №17  Гость FloreneBolick34 23-12-2020 Цитировать
      It's nearly impossible to find knowledgeable people in this particular topic, however, you seem like you know what you're talking about! Thanks
    1. №18  Гость FloreneBolick34 26-12-2020 Цитировать
      If some one wishes to be updated with most up-to-date technologies after that he must be visit this web site and be up to date daily.
    1. №19  Гость FloreneBolick34 26-12-2020 Цитировать
      Hey would you mind sharing which blog platform you're working with? I'm looking to start my own blog soon but I'm having a tough time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I'm looking for something completely unique. P.S My apologies for getting off-topic but I had to ask!
    1. №20  Гость FloreneBolick34 28-12-2020 Цитировать
      Hi there very cool blog!! Guy .. Excellent .. Superb .. I will bookmark your website and take the feeds additionally? I'm glad to find numerous helpful info right here within the submit, we'd like work out more strategies in this regard, thank you for sharing. . . . . .
    1. №21  Гость FloreneBolick34 29-12-2020 Цитировать
      You should take part in a contest for one of the most useful websites online. I will highly recommend this blog!
    1. №22  Гость HelenCoughlin 02-01-2021 Цитировать
      Hello there I am so excited I found your blog, I really found you by accident, while I was browsing on Aol for something else, Anyways I am here now and would just like to say thanks a lot for a tremendous post and a all round exciting blog (I also love the theme/design), I don't have time to go through it all at the moment but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the great job.

      Post writing is also a excitement, if you be acquainted with afterward you can write otherwise it is difficult to write.

      I was able to find good information from your articles.

      I think the admin of this web site is really working hard in favor of his web site, for the reason that here every information is quality based information.
    1. №23  Гость HelenCoughlin 03-01-2021 Цитировать
      I love what you guys tend to be up too. This type of clever work and reporting! Keep up the superb works guys I've included you guys to blogroll.

      excellent publish, very informative. I ponder why the other specialists of this sector do not understand this. You must proceed your writing. I am sure, you have a great readers' base already!

      It is not my first time to pay a visit this site, i am visiting this web site dailly and get good facts from here everyday.

      Hello Dear, are you really visiting this website on a regular basis, if so afterward you will absolutely obtain good knowledge.

      Asking questions are genuinely pleasant thing if you are not understanding something entirely, however this article provides fastidious understanding yet.

      Outstanding post but I was wondering if you could write a litte more on this subject? I'd be very thankful if you could elaborate a little bit further. Thanks!

      Heya i am for the primary time here. I came across this board and I in finding It really helpful & it helped me out much. I'm hoping to give something again and aid others like you helped me.
    1. №24  Гость AhmedHorne518 04-01-2021 Цитировать
      Your roofing contractor in Portland will install roof vents to help circulate air and prevent condensation. Carefully come down off the roof and remove the ladder. An experienced professional will however give quick answers that are very accurate and straight to the point.
    1. №25  Гость AhmedHorne518 04-01-2021 Цитировать
      When you go onto the roof of the mobile home, use a ladder tall enough to get up there. While looking for the contractor, have the bids from at least three contractors and decide for the best one. How costly will repairs be if you select basic asphalt roofing.
    1. №26  Гость LeonelNdz221659 04-01-2021 Цитировать
      With honeycomb construction and double-pane glass you get style and quality, guaranteed. 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. 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. №27  Гость AhmedHorne518 05-01-2021 Цитировать
      Once you have recognized the areas for roof repair, you need to find out if this problem is a result of bad weather conditions or the roof structure itself. It plays the role of an asylum that defends the dwelling from inclemency and other troubles. Start with the obvious,are there any torn,broken,or missing shingles.
    1. №28  Гость AhmedHorne518 05-01-2021 Цитировать
      Sometimes, this can be done due to localized damage such as missed or cracked shakes or shingles, or on a flat roof, a blistered or cracked area. While looking for the contractor, have the bids from at least three contractors and decide for the best one. Before you move out to get those quote, it is important for you to up the requirements within the job, including when work must begin, when the repair is required to be complete, and any preferences you could have as to roofing components.

      Steve Slepcevic's team of insurance claim consultants re-filed the claim documenting the original damage along with the additional mold damage and won a settlement of $380,000 for the client. For camper trailers, trailer roof repair starts with a good old fashioned cleaning. How costly will repairs be if you select basic asphalt roofing.

      Slide the straight end of a pry bar under the shingle to be removed and pry up the nails. An expert roofer will also take the time to consult with you personally to determine your vision and preferences for your home’s roof. But like the sloped rooftop, flat roofs could receive damaged and so need rooftop fix.

      When looking for a roofing professional, it is important to compare the rates and services of a few providers before hiring a company. It plays the role of an asylum that defends the dwelling from inclemency and other troubles. Before you move out to get those quote, it is important for you to up the requirements within the job, including when work must begin, when the repair is required to be complete, and any preferences you could have as to roofing components.

      Once you have recognized the areas for roof repair, you need to find out if this problem is a result of bad weather conditions or the roof structure itself. It plays the role of an asylum that defends the dwelling from inclemency and other troubles. Flashing refers to the materials used for a roofing installation that create waterproof transitions between roofing materials and roof protrusions, such as a chimney or air vent.
    1. №29  Гость FloreneBolick34 06-01-2021 Цитировать
      Wow that was unusual. I just wrote an incredibly long comment but after I clicked submit my comment didn't appear. Grrrr... well I'm not writing all that over again. Anyhow, just wanted to say superb blog!
    1. №30  Гость FloreneBolick34 09-01-2021 Цитировать
      This info is priceless. When can I find out more?
1 2 3 4 5
Имя:*
Комментарий:
Сервис не доступен
Похожие статьи:
  • Как закрыть ссылку от индексации при помощи javascript
  • Всплывающее окно jquery на сайте
  • 10 новых jQuery плагинов 2014 года
  • Красивое вертикальное меню на CSS
  • Горизонтальное меню на CSS
  • Популярное
  • Авторизация
Войти
Забыли? Регистрация
HashFlare
  • Обратная связь
  • Карта сайта
При копировании материалов ссылка на источник Artinblog.ru обязательна. Copyright © 2012 - 2015