
Я решил показать вам, как создать эффект раздвижная дверь (развигаться будут от центра четыре угла).
Что делает наш скрипт:
- Берём все DIV с классом qitem, находим образ слоя и меняем его на четыре DIVs (четыре угла).
- Каждый угл будет иметь то же фоновое изображение, но с разным положением: вверху слева, вверху справа, внизу слева и внизу справа. Это будет по-прежнему похоже на изначальное все изображение, однако, изображение фактически будет заменено новым DIV и разделено на четыре части.
- При событии наведении мыши наш блок будет двигать углы по диагонали.
- Описание блока будет отображаться после того как углы разъедутся.
- Если пользователь нажал на блок, он будет перемещён по заданной нами ссылке.
На следующем рисунке показано схематически, как это работает:
1. HTML
Это хорошая практика, чтобы написать HTML код как можно более простым. HTML можно упростить всегда, используя CSS и Javascript. В результате когда мы упростим HTML для одного элемента — мы сможем дублировать его код столько раз, сколько нам потребуется.
1 2 3 4 |
<div class="qitem"> <a href="http://www.google.com"><img src="1.gif" alt="Test 1" title="" width="126" height="126"/></a> <span class="caption"><h4>Элемент 1</h4><p>Текст описание нашего блока.</p></span> </div> |
2. CSS
С CSS тоже всё довольно просто. У нас есть класс с именем qitem. Наш класс qitem должен иметь свойства: скрытый, чтобы скрыть эти четыре угла, плавающим для создания Milti строк и столбцов, иметь курсор в виде руки при наведении, чтобы пользователь понимал что имеет дело с ссылкой.
Для заголовка, позицию прописываем снова абсолютную, а также ставим обязательно Z-index, т.к. наша надпись должна быть многоуровневой в рамках четырех углов.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
body { font-family:arial; } .qitem { /* width and height must be even number */ width:126px; height:126px; /* some styling for the item */ border:4px solid #222; margin:5px 5px 5px 0; background: url('bg.gif') no-repeat; /* make sure the four divs are hidden after changing the position */ overflow:hidden; /* absolute position enabled for children elements*/ position:relative; /* display item in single row */ float:left; /* hand symbol for ie and other browser */ cursor:hand; cursor:pointer; } .qitem img { border:0; } /* styling for caption, position absolute is a must to set the z-index */ .qitem .caption { position:absolute; z-index:0; color:#ccc; display:block; } .qitem .caption h4 { font-size:12px; padding:10px 5px 0 8px; margin:0; color:#369ead; } .qitem .caption p { font-size:10px; padding:3px 5px 0 8px; margin:0; } /* Generic setting for corners */ .topLeft, .topRight, .bottomLeft, .bottomRight { /* allow javascript to move the corners */ position:absolute; background-repeat: no-repeat; z-index:200; } /* set the background position for different corners */ .topLeft { background-position: top left; } .topRight { background-position: top right; } .bottomLeft { background-position: bottom left; } .bottomRight { background-position: bottom right; } .clear { clear:both; } |
3. Javascript
Итак что делает наш Javascript:
- Когда документ будет готов, он вычисляет положение всех углов.
- Использование each() в цикле:
- Захватить все элементы: путь к изображению.
- Берём IMG элемент
- Добавляем четыре угла
- Устанавливаем фоновое изображение (образ пути берем из IMG элемент) для всех углов
- Установливаем положение во всех уголках
- * В связи с совместимостью IE7, вы должны убедиться, что размер изображения / qitem является четным числом, для того чтобы была возможность разделить значение целое число. IE7 может не верно отработать.
- На события мыши: указать верные значения для всех углов и анимировать сдвиг углов от qitem.
- На событие увода мыши с блока: сбросить все углы и анимировать их так, чтобы углы возвратились туда, где были.
- По щелчку: выполнить переход по ссылке.
На следующем рисунке иллюстрирую расчет:
В приведенном ниже JavaScript, у нас есть раздел для расчета. Если вы посмотрите на картинки выше, то увидите что если предположим ширина элемента 126px, то значения, которые мы должны генерировать является 0px, 63px, -63px и 126px
Таким образом, (размер элемента мы использовали в этом учебнике, 126px)
- var neg = Math.round($(‘.qitem’).width() / 2) * (-1);
(126 / 2) * (-1), neg = -63px - var pos = neg * (-1);
neg = -63px, pos = (-63) * -(1), pos = 63px - var out = pos * 2;
pos = 63px, pos = 63 * 2, pos = 126px
Теперь мы знаем, все математические расчеты, как должно это работает. Пора объединить все в единое целое!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
$(document).ready(function() { //Custom settings var style_in = 'easeOutBounce'; var style_out = 'jswing'; var speed_in = 1000; var speed_out = 300; //Calculation for corners var neg = Math.round($('.qitem').width() / 2) * (-1); var pos = neg * (-1); var out = pos * 2; $('.qitem').each(function () { //grab the anchor and image path url = $(this).find('a').attr('href'); img = $(this).find('img').attr('src'); //remove the image $('img', this).remove(); //append four corners/divs into it $(this).append('<div class="topLeft"></div><div class="topRight"></div><div class="bottomLeft"></div><div class="bottomRight"></div>'); //set the background image to all the corners $(this).children('div').css('background-image','url('+ img + ')'); //set the position of corners $(this).find('div.topLeft').css({top:0, left:0, width:pos , height:pos}); $(this).find('div.topRight').css({top:0, left:pos, width:pos , height:pos}); $(this).find('div.bottomLeft').css({bottom:0, left:0, width:pos , height:pos}); $(this).find('div.bottomRight').css({bottom:0, left:pos, width:pos , height:pos}); }).hover(function () { //animate the position $(this).find('div.topLeft').stop(false, true).animate({top:neg, left:neg}, {duration:speed_out, easing:style_out}); $(this).find('div.topRight').stop(false, true).animate({top:neg, left:out}, {duration:speed_out, easing:style_out}); $(this).find('div.bottomLeft').stop(false, true).animate({bottom:neg, left:neg}, {duration:speed_out, easing:style_out}); $(this).find('div.bottomRight').stop(false, true).animate({bottom:neg, left:out}, {duration:speed_out, easing:style_out}); }, function () { //put corners back to the original position $(this).find('div.topLeft').stop(false, true).animate({top:0, left:0}, {duration:speed_in, easing:style_in}); $(this).find('div.topRight').stop(false, true).animate({top:0, left:pos}, {duration:speed_in, easing:style_in}); $(this).find('div.bottomLeft').stop(false, true).animate({bottom:0, left:0}, {duration:speed_in, easing:style_in}); $(this).find('div.bottomRight').stop(false, true).animate({bottom:0, left:pos}, {duration:speed_in, easing:style_in}); }).click (function () { //go to the url window.location = $(this).find('a').attr('href'); }); }); |
college term paper writers within paper-writer.org