В этой статье мы разберем не только, как создавать эффекты движения фоновых изображений, но и расскажем, как их настраивать (вертикальное, горизонтальное или диагональное движение).
Хотя, концепция анимации и выглядит очень просто, но зато она занимательна для новичков...
HTML
Ничего лишнего в HTML коде. Мы поместим фоновое изображение в элемент div
с классом cloud
и анимируем его.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Scrolling Backgorund</title> </head> <body> <div> </div> </body> </html> |
CSS
CSS код такой же короткий.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
body { margin:0; padding:0; background:#fff; } .clouds { width:300px; height:300px; margin:10px; border:2px solid #ccc; background:#3e83c8 url(images/bg_clouds.png) repeat-x 0 bottom; } |
Javascript
Эта часть кода наполняет наш элемент жизнью. Мы сделаем этот код легко настраиваемым. Можно будет управлять и скоростью и направлением движения.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$(document).ready(function () { // speed in milliseconds var scrollSpeed = 70; // set the direction var direction = 'h'; // set the default position var current = 0; function bgscroll(){ // 1 pixel row at a time current -= 1; // move the background with backgrond-position css properties $('div.clouds').css("backgroundPosition", (direction == 'h') ? current+"px 0" : "0 " + current+"px"); } //Calls the scrolling function repeatedly var init = setInterval("bgscroll()", scrollSpeed); }); |
Плагин
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 |
(function() { $.fn.bgscroll = $.fn.bgScroll = function( options ) { if( !this.length ) return this; if( !options ) options = {}; if( !window.scrollElements ) window.scrollElements = {}; for( var i = 0; i < this.length; i++ ) { var allowedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var randomId = ''; for( var l = 0; l < 5; l++ ) randomId += allowedChars.charAt( Math.floor( Math.random() * allowedChars.length ) ); this[ i ].current = 0; this[ i ].scrollSpeed = options.scrollSpeed ? options.scrollSpeed : 70; this[ i ].direction = options.direction ? options.direction : 'h'; window.scrollElements[ randomId ] = this[ i ]; eval( 'window[randomId]=function(){var axis=0;var e=window.scrollElements.' + randomId + ';e.current -= 1;if (e.direction == "h") axis = e.current + "px 0";else if (e.direction == "v") axis = "0 " + e.current + "px";else if (e.direction == "d") axis = e.current + "px " + e.current + "px";$( e ).css("background-position", axis);}' ); setInterval( 'window.' + randomId + '()', options.scrollSpeed ? options.scrollSpeed : 70 ); } return this; } })(jQuery); |
Использование
И так, поехали! Убедитесь, что у вас подключены плагины jQuery и bgscroll. Все настраивается двумя свойствами:
- scrollSpeed : скорость перемещения
- direction : направление движения может принимать следующие значения: «v», «h» или «d» (вертикаль, горизонталь или диагональ)
1 2 3 4 |
$( function() { $('.clouds1').bgscroll({scrollSpeed:10 , direction:'h' }); $('.clouds2').bgscroll({direction:'d'}); }); |
Заключение
Мы надеемся, что плагин будет для вас полезен. Спасибо.
хм...
Эээ... чот не работает( Я код плагина запихнул в отдельный файл js, который подключил к основному документу, а первый блок с кодом JS просто вставил перед закрывающим body в теге ... консоль выдаёт, что bgscroll undefined. Причём очень много раз — видимо, каждый раз, когда значение бэкграунд-позишна пытается измениться на один пиксель...