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

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

admin 132 354
  • 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. №31  Гость FloreneBolick34 11-01-2021 Цитировать
      I'm impressed, I must say. Rarely do I encounter a blog that's equally educative and entertaining, and without a doubt, you've hit the nail on the head. The problem is something not enough people are speaking intelligently about. I am very happy I stumbled across this in my hunt for something relating to this.
    1. №32  Гость FloreneBolick34 11-01-2021 Цитировать
      Hi to all, how is all, I think every one is getting more from this web site, and your views are nice for new people.
    1. №33  Гость FloreneBolick34 11-01-2021 Цитировать
      Heya great website! Does running a blog such as this require a great deal of work? I have virtually no understanding of programming however I had been hoping to start my own blog soon. Anyhow, should you have any ideas or tips for new blog owners please share. I understand this is off topic but I just needed to ask. Appreciate it!
    1. №34  Гость FloreneBolick34 13-01-2021 Цитировать
      Hi, I do believe this is a great blog. I stumbledupon it ;) I may return yet again since I book marked it. Money and freedom is the best way to change, may you be rich and continue to help other people.
    1. №35  Гость FloreneBolick34 13-01-2021 Цитировать
      I every time emailed this blog post page to all my contacts, since if like to read it then my contacts will too.
    1. №36  Гость FloreneBolick34 14-01-2021 Цитировать
      Pretty! This has been an extremely wonderful article. Thank you for providing these details.
    1. №37  Гость FloreneBolick34 16-01-2021 Цитировать
      Awesome blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple tweeks would really make my blog jump out. Please let me know where you got your theme. Thanks
    1. №38  Гость FloreneBolick34 17-01-2021 Цитировать
      I like what you guys are up too. Such clever work and exposure! Keep up the great works guys I've included you guys to my blogroll.
    1. №39  Гость FloreneBolick34 28-01-2021 Цитировать
      With havin so much written content do you ever run into any problems of plagorism or copyright infringement? My blog has a lot of unique content I've either written myself or outsourced but it appears a lot of it is popping it up all over the internet without my agreement. Do you know any methods to help reduce content from being stolen? I'd really appreciate it.
    1. №40  Гость FloreneBolick34 02-02-2021 Цитировать
      I'm impressed, I have to admit. Seldom do I come across a blog that's equally educative and amusing, and let me tell you, you have hit the nail on the head. The issue is an issue that too few people are speaking intelligently about. I am very happy I found this in my search for something concerning this.
    1. №41  Гость FloreneBolick34 16-02-2021 Цитировать
      This page definitely has all the information I needed about this subject and didn't know who to ask.
    1. №42  Palma 20-02-2021 Цитировать
      I was recommended this web site via my cousin. I am no longer positive whether or not this submit is written by way of him as no one else know such special about my difficulty. You're amazing! Thank you! Feel free to surf to my webpage; ______
    1. №43  Dena 21-02-2021 Цитировать
      Thanks for finally writing about >        jQuery qTip.  ? <Liked it! Also visit my blog post; ______
    1. №44  Гость FloreneBolick34 23-02-2021 Цитировать
      I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz respond as I'm looking to create my own blog and would like to know where u got this from. thanks a lot
    1. №45  Гость FloreneBolick34 23-02-2021 Цитировать
      If some one wants to be updated with latest technologies then he must be go to see this site and be up to date everyday.
    1. №46  Гость FloreneBolick34 23-02-2021 Цитировать
      I do not even know how I ended up here, but I thought this post was good. I do not know who you are but definitely you're going to a famous blogger if you are not already ;) Cheers!
    1. №47  Гость FloreneBolick34 24-02-2021 Цитировать
      I was able to find good information from your content.
    1. №48  Гость FloreneBolick34 25-02-2021 Цитировать
      I'm not sure why but this website is loading incredibly slow for me. Is anyone else having this issue or is it a issue on my end? I'll check back later on and see if the problem still exists.
    1. №49  Гость FloreneBolick34 25-02-2021 Цитировать
      It is in point of fact a nice and helpful piece of information. I'm glad that you shared this helpful info with us. Please stay us informed like this. Thank you for sharing.
    1. №50  Гость FloreneBolick34 27-02-2021 Цитировать
      Hi there, I found your blog by the use of Google while searching for a comparable matter, your web site came up, it appears great. I've bookmarked it in my google bookmarks. Hello there, just become aware of your weblog via Google, and found that it's truly informative. I'm going to watch out for brussels. I'll appreciate if you continue this in future. A lot of other people will likely be benefited from your writing. Cheers!
    1. №51  Гость FloreneBolick34 28-02-2021 Цитировать
      Hi there! I know this is kinda off topic however , I'd figured I'd ask. Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa? My website goes over a lot of the same subjects as yours and I feel we could greatly benefit from each other. If you might be interested feel free to send me an email. I look forward to hearing from you! Wonderful blog by the way!
    1. №52  Гость FloreneBolick34 28-02-2021 Цитировать
      Quality posts is the secret to interest the people to pay a visit the web site, that's what this site is providing.
    1. №53  Гость FloreneBolick34 28-02-2021 Цитировать
      Good post however , I was wanting to know if you could write a litte more on this topic? I'd be very grateful if you could elaborate a little bit further. Cheers!
    1. №54  Гость FloreneBolick34 03-03-2021 Цитировать
      I know this if off topic but I'm looking into starting my own blog and was wondering what all is needed to get set up? I'm assuming having a blog like yours would cost a pretty penny? I'm not very internet savvy so I'm not 100% certain. Any recommendations or advice would be greatly appreciated. Cheers
    1. №55  Гость FloreneBolick34 03-03-2021 Цитировать
      Hi there, I found your blog by the use of Google while searching for a related subject, your site got here up, it appears to be like great. I have bookmarked it in my google bookmarks. Hello there, just turned into alert to your weblog via Google, and located that it's really informative. I am gonna be careful for brussels. I'll be grateful when you proceed this in future. A lot of other people can be benefited from your writing. Cheers!
    1. №56  Гость FloreneBolick34 04-03-2021 Цитировать
      Hurrah! Finally I got a webpage from where I be able to genuinely take helpful facts regarding my study and knowledge.
    1. №57  Гость FloreneBolick34 04-03-2021 Цитировать
      Have you ever thought about publishing an ebook or guest authoring on other blogs? I have a blog centered on the same ideas you discuss and would really like to have you share some stories/information. I know my readers would appreciate your work. If you're even remotely interested, feel free to send me an e-mail.
    1. №58  Гость FloreneBolick34 06-03-2021 Цитировать
      I think this is among the most significant information for me. And i'm glad reading your article. But should remark on few general things, The website style is great, the articles is really great : D. Good job, cheers
    1. №59  Гость FloreneBolick34 06-03-2021 Цитировать
      Please let me know if you're looking for a article writer for your blog. You have some really great articles and I feel I would be a good asset. If you ever want to take some of the load off, I'd really like to write some articles for your blog in exchange for a link back to mine. Please shoot me an email if interested. Thanks!
    1. №60  Гость FloreneBolick34 06-03-2021 Цитировать
      I know this if off topic but I'm looking into starting my own weblog and was wondering what all is required to get set up? I'm assuming having a blog like yours would cost a pretty penny? I'm not very internet smart so I'm not 100% positive. Any tips or advice would be greatly appreciated. Cheers

      Way cool! Some extremely valid points! I appreciate you penning this article plus the rest of the website is extremely good.
1 2 3 4 5
Имя:*
Комментарий:
Сервис не доступен
Похожие статьи:
  • Как закрыть ссылку от индексации при помощи javascript
  • Всплывающее окно jquery на сайте
  • 10 новых jQuery плагинов 2014 года
  • Красивое вертикальное меню на CSS
  • Горизонтальное меню на CSS
  • Популярное
  • Авторизация
Войти
Забыли? Регистрация
HashFlare
  • Обратная связь
  • Карта сайта
При копировании материалов ссылка на источник Artinblog.ru обязательна. Copyright © 2012 - 2015