Красивый вывод дополнительной информации при наведении
И снова приветствую вас на своем блоге, посвященному созданию блога на wordpress, продвижению и заработке на нем!
Как и обещал в прошлом уроке — сегодня я вам покажу как сделать прикольный вывод информации на картинке (например в галерее) при наведении курсора.
И основная идея в том, что бы эта информация выезжала (и пряталась) с той стороны, куда мы двигаем курсор мыши. Для реализации такого эффекта будут использованы jQuery и CSS3.
Такой эффект можно использовать для своего портфолио или же для галереи изображений.
И так, начнем…
1. Делаем HTML разметку
Используем неупорядоченный список с миниатюрами и перекрывающим блоком внутри, который и содержит дополнительную информацию.
<ul id="da-thumbs" class="da-thumbs"> <li> <a href="#"> <img src="images/1.jpg" /> <div><span>Menu by Simon Jensen</span></div> </a> </li> <li> <a href="#"> <img src="images/2.jpg" /> <div><span>TN Aquarium by Charlie Gann</span></div> </a> </li> <li> <a href="#"> <img src="images/3.jpg" /> <div><span>Mr. Crabs by John Generalov</span></div> </a> </li> <li> <a href="#"> <img src="images/4.jpg" /> <div><span>Gallery of Mo 2.Mo logo by Adam Campion</span></div> </a> </li> <li> <a href="#"> <img src="images/5.jpg" /> <div><span>Ice Cream - nom nom by Eight Hour Day</span></div> </a> </li> <li> <a href="#"> <img src="images/6.jpg" /> <div><span>My Muse by Zachary Horst</span></div> </a> </li> <li> <a href="#"> <img src="images/7.jpg" /> <div><span>Natalie & Justin Cleaning by Justin Younger</span></div> </a> </li> <li> <a href="#"> <img src="images/8.jpg" /> <div><span>App Preview by Ryan Deshler</span></div> </a> </li> <li> <a href="#"> <img src="images/9.jpg" /> <div><span>Cornwall Map by Katharina Maria Zimmermann</span></div> </a> </li> <li> <a href="#"> <img src="images/10.jpg" /> <div><span>final AD logo by Annette Diana</span></div> </a> </li> <li> <a href="#"> <img src="images/11.jpg" /> <div><span>Land Those Planes by Lee Ann Marcel</span></div> </a> </li> <li> <a href="#"> <img src="images/12.jpg" /> <div><span>Seahorse by Trevor Basset</span></div> </a> </li> </ul>
2. Стили оформления
Элементам списка ставим обтекание слева и относительное позиционирование, а для блока с дополнительной информацией абсолютное позиционирование и 100% высоту и ширину.
.da-thumbs li a div { top: 0px; left: -100%; -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; -ms-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; } .da-thumbs li a:hover div{ left: 0px; } .da-thumbs { list-style: none; width: 984px; height: 600px; position: relative; margin: 20px auto; padding: 0; } .da-thumbs li { float: left; margin: 5px; background: #fff; padding: 8px; position: relative; box-shadow: 0 1px 3px rgba(0,0,0,0.1); } .da-thumbs li a, .da-thumbs li a img { display: block; position: relative; } .da-thumbs li a { overflow: hidden; } .da-thumbs li a div { position: absolute; background: #333; background: rgba(75,75,75,0.7); width: 100%; height: 100%; } .da-thumbs li a div span { display: block; padding: 10px 0; margin: 40px 20px 20px 20px; text-transform: uppercase; font-weight: normal; color: rgba(255,255,255,0.9); text-shadow: 1px 1px 1px rgba(0,0,0,0.2); border-bottom: 1px solid rgba(255,255,255,0.5); box-shadow: 0 1px 0 rgba(0,0,0,0.1), 0 -10px 0 rgba(255,255,255,0.3); }
3. JavaScript
Подключаем саму библиотеку jQuery, если она у Вас еще не подключена:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
и сам скрипт, назовем его jquery.hoverdir.js (скрипт привожу полностью, даже с комментариями, чтобы избежать разных ошибок в коде).
( function( $, window, undefined ) { 'use strict'; $.HoverDir = function( options, element ) { this.$el = $( element ); this._init( options ); }; // the options $.HoverDir.defaults = { speed : 300, easing : 'ease', hoverDelay : 0, inverse : false }; $.HoverDir.prototype = { _init : function( options ) { // options this.options = $.extend( true, {}, $.HoverDir.defaults, options ); // transition properties this.transitionProp = 'all ' + this.options.speed + 'ms ' + this.options.easing; // support for CSS transitions this.support = Modernizr.csstransitions; // load the events this._loadEvents(); }, _loadEvents : function() { var self = this; this.$el.on( 'mouseenter.hoverdir, mouseleave.hoverdir', function( event ) { var $el = $( this ), $hoverElem = $el.find( 'div' ), direction = self._getDir( $el, { x : event.pageX, y : event.pageY } ), styleCSS = self._getStyle( direction ); if( event.type === 'mouseenter' ) { $hoverElem.hide().css( styleCSS.from ); clearTimeout( self.tmhover ); self.tmhover = setTimeout( function() { $hoverElem.show( 0, function() { var $el = $( this ); if( self.support ) { $el.css( 'transition', self.transitionProp ); } self._applyAnimation( $el, styleCSS.to, self.options.speed ); } ); }, self.options.hoverDelay ); } else { if( self.support ) { $hoverElem.css( 'transition', self.transitionProp ); } clearTimeout( self.tmhover ); self._applyAnimation( $hoverElem, styleCSS.from, self.options.speed ); } } ); }, // credits : http://stackoverflow.com/a/3647634 _getDir : function( $el, coordinates ) { // the width and height of the current div var w = $el.width(), h = $el.height(), // calculate the x and y to get an angle to the center of the div from that x and y. // gets the x value relative to the center of the DIV and "normalize" it x = ( coordinates.x - $el.offset().left - ( w/2 )) * ( w > h ? ( h/w ) : 1 ), y = ( coordinates.y - $el.offset().top - ( h/2 )) * ( h > w ? ( w/h ) : 1 ), // the angle and the direction from where the mouse came in/went out clockwise (TRBL=0123); // first calculate the angle of the point, // add 180 deg to get rid of the negative values // divide by 90 to get the quadrant // add 3 and do a modulo by 4 to shift the quadrants to a proper clockwise TRBL (top/right/bottom/left) **/ direction = Math.round( ( ( ( Math.atan2(y, x) * (180 / Math.PI) ) + 180 ) / 90 ) + 3 ) % 4; return direction; }, _getStyle : function( direction ) { var fromStyle, toStyle, slideFromTop = { left : '0px', top : '-100%' }, slideFromBottom = { left : '0px', top : '100%' }, slideFromLeft = { left : '-100%', top : '0px' }, slideFromRight = { left : '100%', top : '0px' }, slideTop = { top : '0px' }, slideLeft = { left : '0px' }; switch( direction ) { case 0: // from top fromStyle = !this.options.inverse ? slideFromTop : slideFromBottom; toStyle = slideTop; break; case 1: // from right fromStyle = !this.options.inverse ? slideFromRight : slideFromLeft; toStyle = slideLeft; break; case 2: // from bottom fromStyle = !this.options.inverse ? slideFromBottom : slideFromTop; toStyle = slideTop; break; case 3: // from left fromStyle = !this.options.inverse ? slideFromLeft : slideFromRight; toStyle = slideLeft; break; }; return { from : fromStyle, to : toStyle }; }, // apply a transition or fallback to jquery animate based on Modernizr.csstransitions support _applyAnimation : function( el, styleCSS, speed ) { $.fn.applyStyle = this.support ? $.fn.css : $.fn.animate; el.stop().applyStyle( styleCSS, $.extend( true, [], { duration : speed + 'ms' } ) ); }, }; var logError = function( message ) { if ( window.console ) { window.console.error( message ); } }; $.fn.hoverdir = function( options ) { var instance = $.data( this, 'hoverdir' ); if ( typeof options === 'string' ) { var args = Array.prototype.slice.call( arguments, 1 ); this.each(function() { if ( !instance ) { logError( "cannot call methods on hoverdir prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for hoverdir instance" ); return; } instance[ options ].apply( instance, args ); }); } else { this.each(function() { if ( instance ) { instance._init(); } else { instance = $.data( this, 'hoverdir', new $.HoverDir( options, this ) ); } }); } return instance; }; } )( jQuery, window );
Теперь для того, что бы все заработало нужно добавить следующий код, после тех скриптов которые мы подключали выше. Всего в примере 3 разных эффекта. И я их выложу по порядку, так как иони идут на странице демонстрации.
1 Скрипт — По умолчанию
<script type="text/javascript"> $(function() { $(' #da-thumbs > li ').each( function() { $(this).hoverdir(); } ); }); </script>
2 Скрипт — С задержкой
<script type="text/javascript"> $(function() { $(' #da-thumbs > li ').each( function() { $(this).hoverdir({ hoverDelay : 75 }); } ); }); </script>
3 Скрипт — Инверсия
<script type="text/javascript"> $(function() { $(' #da-thumbs > li ').each( function() { $(this).hoverdir({ hoverDelay : 50, inverse : true }); } ); }); </script>
На этом все… Надеюсь Вам это было полезным!
С вами был — ваш Юрич!
Увидеть бы, что должно получиться, а то не понятно. хочу я такое или не хочу.