Полезное в сети

Всегда в теме

Статистика


Яндекс.Метрика


Онлайн всего: 1
Гостей: 1
Пользователей: 0

Рекомендуем



Главная » 2013 » Ноябрь » 27 » Анимированные закладки с JQuery и CSS


20:00
Анимированные закладки с JQuery и CSS

Анимированные закладки с JQuery и CSS

 

 


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

ДЕМО                       СКАЧАТЬ

Шаг 1 - HTML

Как обычно, мы начинаем с разметки HTML. Площадь обмена  строится с использованием трех основных DIV контейнеров:

  • # share - этот элемент действует как контейнер, который держит два  других. А также некоторые свойства CSS3, например, закругленные углы;
  • # stage - При загрузке страницы JQuery обнаруживает горизонтальные и вертикальные центры и использует их в положение вращающихся DIV. А также движение влево;
  • # share-label- «Поделитесь сообщением" изображение в качестве фона. Он также определяет движение влево, таким образом, расположен прямо рядом с # stage.

demo.html

<div id="share">

<div id="stage">

 

<div class="btn digg"><div class="bcontent"><a class="DiggThisButton"></a><script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></div></div>

<div class="btn tweetmeme"><div class="bcontent"><script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script></div></div>

<div class="btn dzone"><div class="bcontent"><script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script></div></div>

<div class="btn reddit"><div class="bcontent"><script type="text/javascript" src="http://www.reddit.com/button.js?t=2"></script></div></div>

<div class="btn facebook"><div class="bcontent"><a name="fb_share" type="box_count" href="http://www.facebook.com/sharer.php">Share</a><script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script></div></div>

 

</div>

 

<div id="share-label">

<!-- This is where the share some love image appears -->

</div>

 

</div>

 

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

Каждая кнопка имеет общий ПК класс и один индивидуальный (Digg, Tweetmeme, и т.д.). Это дает возможность собрать общие правила, для кнопок в одном классе и сделать легче настройки на более позднее время.

 


Шаг 2 - CSS

Я разделил код CSS на две части.

файле demo.css - Часть 1

#share{

    /* The share box container */

    width:500px;

    background:#ececec;

    height:220px;

    margin:60px auto;

    overflow:hidden;

 

    -moz-border-radius:12px;

    -webkit-border-radius:12px;

    border-radius:12px;

}

 

#share-label{

    /* The image on the right */

    background:url(img/share.png) no-repeat 50% 50%;

    float:left;

    height:220px;

    width:200px;

}

 

#stage{

    /* This is where the animation takes place */

    position:relative;

 

    border-right:1px solid #DDDDDD;

    width:290px;

    height:220px;

    background:white;

    float:left;

 

    border-bottom-left-radius:12px;

    border-top-left-radius:12px;

 

    -moz-border-radius-bottomleft:12px;

    -moz-border-radius-topleft:12px;

 

    -webkit-border-bottom-left-radius:12px;

    -webkit-border-top-left-radius:12px;

}

 

.btn{

    /* This class is assigned to every share button */

    background-color:white;

    height:90px;

    left:0;

    top:0;

    width:60px;

    position:relative;

    margin:20px 0 0 10px;

    float:left;

}

 

.bcontent{

    /* Positioned inside the .btn container */

    position:absolute;

    top:auto;

    bottom:20px;

    left:0;

}

 

Может быть, на данном этапе вам интересно, как фактические кнопки анимированы в круговом движении на странице.

Большая часть техники происходит внутри # stage класса CSS. Сама сцена позиционирована относительно, что позволяет кнопкам (которые имеют абсолютное позиционирование, является прямыми наследниками) они должны быть расположены соответственно.

Это означает, что установка верхней и левой кнопки к нулю, позиционирует их в левом верхнем углу сцены.

 

demo.css - Часть 2

/* Individual rules for every share button */

 

.digg{    background:url(img/digg_reflection.png) no-repeat -4px bottom;}

.reddit{                background:url(img/reddit_reflection.png) no-repeat -4px bottom;}

.facebook{         background:url(img/facebook_reflection.png) no-repeat bottom center;}

.tweetmeme{   background:url(img/twit_reflection.png) no-repeat -5px bottom;}

.dzone{                background:url(img/dzone_reflection.png) no-repeat -7px bottom;}

 

.thanksto{

    position:absolute;

    bottom:2px;

    right:4px;

    font-size:10px;

}

 

.thanksto a,.thanksto a:visited{

    color:#BBB;

}

 

/* Customizing the facebook share button */

 

span.fb_share_no_count {

    display:block;

}

 

span.fb_share_count_top.fb_share_no_count {

    line-height:54px;

}

 

span.fb_share_count_nub_top.fb_share_no_count{

    display:none;

}

 

span.fb_share_no_count span.fb_share_count_inner {

    background:#3B5998 url(http://static.fbshare.me/f_only.png) no-repeat scroll 20px 5px;

    display:block;

}

 

   

Во второй части таблицы стилей, мы назначили индивидуальные правила для каждой кнопки, которые определяют уникальное фоновое изображение с отражением. После этого мы настроили кнопку facebook, так что его стиль соответствует остальной части кнопок.

 


Шаг 3 - JQuery

Но прежде чем приступить к работе, мы должны включать в себя два файла сценариев в главе нашей страницы:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript" src="script.js"></script>

 

Первый включает библиотеку JQuery от CDN Google, вторая линия включает в себя наши собственныеscript.js файл:

script.js

$(document).ready(function(){

 

    /* This code is run on page load */

 

    var deg=0;

    var dif=-3;

 

    /* Assigning the buttons to a variable for speed: */

    var arr = $('.btn');

 

    /* Caching the length of the array in a vаriable: */

    var len = arr.length;

 

    /* Finding the centers of the animation container: */

    var centerX = $('#stage').width()/2 - 40;

    var centerY = $('#stage').height()/2 - 60;

 

    /* Applying relative positioning to the buttons: */

    arr.css('position','absolute');

 

    /* The function inside the interval is run 25 times per second */

    setInterval(function(){

 

        /* This forms an area with no activity on mouse move in the middle of the stage */

        if(Math.abs(dif)<0.5) return false;

 

        /* Increment the angle: */

        deg+=dif;

 

        /* Loop through all the buttons: */

        $.each(arr,function(i){

 

            /* Calculate the sine and cosine with the new angle */

            var eSin = Math.sin(((360/len)*i+deg)*Math.PI/180);

            var eCos = Math.cos(((360/len)*i+deg)*Math.PI/180);

 

            /* Setting the css properties */

            $(this).css({

                top:centerY+25*eSin,

                left:centerX+90*eCos,

                opacity:0.8+eSin*0.2,

                zIndex:Math.round(80+eSin*20)

            });

        })

    },40);

 

    /* Detecting the movements of the mouse and speeding up or reversing the rotation accordingly: */

    var over=false;

    $("#stage").mousemove(function(e){

 

        if(!this.leftOffset)

        {

            /* This if section is only run the first time the function is executed. */

            this.leftOffset = $(this).offset().left;

            this.width = $(this).width();

        }

 

        /* If the mouse is over a button, set dif to 0, which halts the animation */

        if(over) dif=0;

        else

            dif = -5+(10*((e.pageX-this.leftOffset)/this.width));

 

        /* In the other case calculate the speed according to the X position of the mouse */

    });

 

    /* Detecting whether the mouse is positioned above a share button: */

    $(".bcontent").hover(

        function(){over=true;dif=0;},

        function(){over=false;}

    );

});

 

Основная идея, это то, что мы используем setInterval что бы создать функцию, которая будет работать каждые 40 миллисекунд. Это означает, что она находится в ведении 25 раз в секунду, или если вы сравните его с кино, это 25 кадров в секунду. Другими словами более чем достаточно, чтобы показать гладкость анимации (при условии, что скорость рендеринга браузера достаточно быстр, и что нет никаких других сценариев).

 

ДЕМО                       СКАЧАТЬ

 

Вывод

В этом уроке мы создали анимированный бар социального обмена, который предлагает посетителям  поделиться статьями по ряду социальных сетей.

Источник

Категория: CSS//HTML//JS | Просмотров: 868 | Добавил: Wrecker | Рейтинг: 0.0/0
Всего комментариев: 0
Добавлять комментарии могут только зарегистрированные пользователи.
[ Регистрация | Вход ]

Поиск

Вход

Гость
  • Вход
  • Регистрация
  • Читаемое

    Категории

    Заходи не жди