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

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

admin 132 351
  • 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качиваний: 433)

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

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

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

    1. №61  Гость LeonelNdz221659 06-03-2021 Цитировать
      You may recycle, use CFCs and compost but have thought that actually growing plants on your roof is too much work. Check if the Denver roof repair company is a member of BBB or not. Defend your dwelling by keeping the roof in very good restore.
    1. №62  Гость LeonelNdz221659 06-03-2021 Цитировать
      With honeycomb construction and double-pane glass you get style and quality, guaranteed. Repairing leaking roofs is one of the most common DIY activities. Defend your dwelling by keeping the roof in very good restore.
    1. №63  Гость FloreneBolick34 07-03-2021 Цитировать
      I drop a comment each time I appreciate a article on a blog or I have something to add to the conversation. Usually it's caused by the sincerness displayed in the post I read. And on this post         jQuery qTip.  ?. I was excited enough to post a comment ;-) I do have a couple of questions for you if you don't mind. Could it be just me or do some of the remarks look as if they are coming from brain dead visitors? :-P And, if you are posting at other online social sites, I'd like to keep up with anything new you have to post. Could you list all of your shared sites like your Facebook page, twitter feed, or linkedin profile?
    1. №64  Гость FloreneBolick34 09-03-2021 Цитировать
      Every weekend i used to pay a quick visit this web page, as i want enjoyment, since this this web site conations in fact nice funny material too.
    1. №65  Гость FloreneBolick34 09-03-2021 Цитировать
      I'm not sure where you're getting your information, but good topic. I needs to spend some time learning more or understanding more. Thanks for excellent information I was looking for this information for my mission.
    1. №66  Calvin 21-04-2021 Цитировать
      Popular Nulled Creatus – Ultimate Multipurpose WordPress Theme Pricing - nulled.cr - Templates for Ecommerce. You can find top 10 templates for Blog CMS.
    1. №67  Amelie 11-05-2021 Цитировать
      2020 Nulled v.3.8.8 Adifier WP Directory Theme Nulled Plugins for Themeforest. search and find top 10 components for Ecommerce softwares.
    1. №68  Гость ChristineCapehar 07-06-2021 Цитировать
      Hi there, its pleasant article regarding media print, we all understand media is a wonderful source of data.

      Wonderful goods from you, man. I have remember your stuff prior to and you are just too wonderful. I really like what you have got here, really like what you're saying and the best way during which you say it. You are making it enjoyable and you still care for to keep it wise. I cant wait to learn far more from you. That is really a great website.
    1. №69  Гость Shasta46D892 28-07-2021 Цитировать
      I visited various websites but the audio feature for audio songs present at this site is really fabulous.

      Very nice post. I just stumbled upon your blog and wished to say that I have really enjoyed surfing around your blog posts. In any case I'll be subscribing to your feed and I hope you write again very soon!
    1. №70  Гость Shasta46D892 29-07-2021 Цитировать
      hello!,I love your writing very a lot! share we communicate extra approximately your post on AOL? I need an expert in this house to unravel my problem. May be that's you! Having a look forward to look you.

      I have been browsing online more than 3 hours today, yet I never found any interesting article like yours. It's pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did, the net will be a lot more useful than ever before.

      Great blog you've got here.. It's difficult to find excellent writing like yours these days. I really appreciate individuals like you! Take care!!

      There's definately a great deal to find out about this issue. I love all the points you made.

      Oh my goodness! Impressive article dude! Thanks, However I am experiencing difficulties with your RSS. I don't know why I am unable to subscribe to it. Is there anybody else having identical RSS problems? Anyone who knows the answer will you kindly respond? Thanx!!

      Hi! I realize this is kind of off-topic but I had to ask. Does building a well-established website like yours take a large amount of work? I am completely new to blogging but I do write in my journal every day. I'd like to start a blog so I can easily share my personal experience and feelings online. Please let me know if you have any kind of suggestions or tips for new aspiring bloggers. Thankyou!

      Very great post. I just stumbled upon your weblog and wanted to mention that I've really enjoyed surfing around your weblog posts. After all I will be subscribing to your rss feed and I am hoping you write once more very soon!
    1. №71  Гость Shasta46D892 31-07-2021 Цитировать
      If some one wishes to be updated with most up-to-date technologies then he must be visit this website and be up to date every day.

      Wow, this paragraph is fastidious, my sister is analyzing such things, thus I am going to inform her.
    1. №72  Гость Shasta46D892 01-08-2021 Цитировать
      Wonderful beat ! I would like to apprentice even as you amend your web site, how could i subscribe for a weblog web site? The account aided me a applicable deal. I had been tiny bit acquainted of this your broadcast offered vivid transparent idea

      Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how can we communicate?
    1. №73  Гость MadieHarvey 20-09-2021 Цитировать
      I do consider all of the ideas you have presented on your post. They're really convincing and can definitely work. Nonetheless, the posts are very quick for beginners. May just you please lengthen them a little from subsequent time? Thanks for the post.
    1. №74  Гость MadieHarvey 20-09-2021 Цитировать
      I was suggested this web site by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my trouble. You are amazing! Thanks!
    1. №75  Гость LeonelNdz221659 18-10-2021 Цитировать
      Ask about the procedures they do when working on a roof Vancouver homes have. 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. №76  Гость LeonelNdz221659 20-10-2021 Цитировать
      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. Repairing leaking roofs is one of the most common DIY activities. Defend your dwelling by keeping the roof in very good restore.
    1. №77  Гость LeonelNdz221659 29-10-2021 Цитировать
      The roof is one of the most important safety features for the stability of a home during unfavorable weather. Check if the Denver roof repair company is a member of BBB or not. Most roofers in Maine also do gutter installations.
    1. №78  Гость LeonelNdz221659 29-10-2021 Цитировать
      The roof is one of the most important safety features for the stability of a home during unfavorable weather. 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. №79  Гость LeonelNdz221659 07-11-2021 Цитировать
      With honeycomb construction and double-pane glass you get style and quality, guaranteed. Check if the Denver roof repair company is a member of BBB or not. All you need to do is go online and search with your local pin code.
    1. №80  Гость LeonelNdz221659 07-11-2021 Цитировать
      Searching online is a great way of checking out a company and what they can offer you. Bath roofing services, roof repair Bath, Avon & Somerset. CIRCULAR 230 DISCLOSURE: Pursuant to Treasury Department guidelines, any federal tax information contained in this article, or any attachment, does not constitute a formal tax opinion.
    1. №81  Гость MadieHarvey 25-11-2021 Цитировать
      This is a very good tip particularly to those new to the blogosphere. Brief but very precise information… Thanks for sharing this one. A must read post!
    1. №82  Гость LeonelNdz221659 30-11-2021 Цитировать
      Homeowners who decide to undergo a strategic default are often guided through the process by companies such as You - Walk - Away. This is not a pleasant situation to be in, but the reality is that you simply have to choice. Roofers should also have liability insurance and an up to date worker's comp certificate.
    1. №83  Гость MadieHarvey 30-11-2021 Цитировать
      I would like to thank you for the efforts you've put in writing this website. I'm hoping to view the same high-grade content from you in the future as well. In truth, your creative writing abilities has inspired me to get my own, personal website now ;)
    1. №84  Гость MadieHarvey 02-12-2021 Цитировать
      I blog quite often and I truly thank you for your information. Your article has truly peaked my interest. I am going to book mark your blog and keep checking for new information about once a week. I subscribed to your RSS feed too.
    1. №85  Гость LeonelNdz221659 06-12-2021 Цитировать
      With honeycomb construction and double-pane glass you get style and quality, guaranteed. Check if the Denver roof repair company is a member of BBB or not. through the pre-punched holes to secure the shingle in place.
    1. №86  Гость MadieHarvey 13-12-2021 Цитировать
      Great beat ! I wish to apprentice even as you amend your web site, how can i subscribe for a blog web site? The account helped me a applicable deal. I have been tiny bit acquainted of this your broadcast provided vivid transparent idea
    1. №87  Гость LeonelNdz221659 13-12-2021 Цитировать
      The roof is one of the most important safety features for the stability of a home during unfavorable weather. 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. Roofers should also have liability insurance and an up to date worker's comp certificate.
    1. №88  Гость MadieHarvey 14-12-2021 Цитировать
      Wow! Finally I got a web site from where I can really obtain valuable information regarding my study and knowledge.
    1. №89  Гость MadieHarvey 14-12-2021 Цитировать
      Nice weblog right here! Also your web site loads up very fast! What host are you the usage of? Can I get your associate hyperlink for your host? I desire my website loaded up as fast as yours lol
    1. №90  Гость LeonelNdz221659 09-01-2022 Цитировать
      Ask about the procedures they do when working on a roof Vancouver homes have. This is not a pleasant situation to be in, but the reality is that you simply have to choice. Defend your dwelling by keeping the roof in very good restore.
1 2 3 4 5
Имя:*
Комментарий:
Сервис не доступен
Похожие статьи:
  • Как закрыть ссылку от индексации при помощи javascript
  • Всплывающее окно jquery на сайте
  • 10 новых jQuery плагинов 2014 года
  • Красивое вертикальное меню на CSS
  • Горизонтальное меню на CSS
  • Популярное
  • Авторизация
Войти
Забыли? Регистрация
HashFlare
  • Обратная связь
  • Карта сайта
При копировании материалов ссылка на источник Artinblog.ru обязательна. Copyright © 2012 - 2015