4 сентября 2013
4728
Изменения фона сайта

Изменения фона сайта

JavaScript
Демонстрация » Скачать »

Для Вас сегодня, я подготовил интересную тему урока изменения фона сайта. Написан скрипт на языке JavaScript, поэтому сразу же изучим его код и разберемся как все устроено. По сути подобных скриптов достаточно много, но допустим, хочу немного отклониться с Вашего согласия от темы и представить скрипт, только не с картинками, а с фоновым видео для сайта, может такая тематика кому-то подойдет больше, так как однотипность все-таки в фоновом представлении имеется.

 

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

 

Шаг первый. Файл fon.js.

 

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

// скрипт работы смены фона
var insp = {
iTimeInterval : 50, // интервал смены изображений
iMaxZoom : 100, // максимальный зум
bHZoom : true, // горизонтальный зум
bVZoom : true, // вертикальный зум
iMode : 2, // варианты смены (1 or 2)
iZStep : 0,
iImgStep : 1, // Четкость смены
oPan : null,
iPanWidth : 0, // ширина изображения
iPanHeight : 0,  // высота изображения
oImgBefore: null,
oImgAfter: null,
oImgSource : null, // проверка ссылок на изображения


// главная функция инициализации
init : function(iMode) {
this.iMode = iMode;
this.oImgSource = document.getElementById
('imgsource').children;
this.oPan = document.getElementById('panel');
this.iPanWidth = this.oPan.offsetWidth;
this.iPanHeight = this.oPan.offsetHeight;

 
// начальные свойства первого изображения элемента
this.oImgBefore = document.createElement('img');
this.oImgBefore.src = this.oImgSource[0].src;
this.oImgBefore.style.top = (this.bVZoom ?
-this.iMaxZoom : 0) + 'px';
this.oImgBefore.style.left = (this.bHZoom ?
-this.iMaxZoom : 0) + 'px';
this.oImgBefore.style.width = (this.bHZoom ?
this.iPanWidth + (2 * this.iMaxZoom) : this.iPanWidth)
 + 'px';
this.oImgBefore.style.height = (this.bVZoom ?
this.iPanHeight + (2 * this.iMaxZoom) : this.iPanWidth)
+ 'px';
this.oImgBefore.style.filter = 'alpha(opacity=1)';
this.oImgBefore.style.opacity = 1;
this.oPan.appendChild(this.oImgBefore);


// начальные свойства второго изображения элемента
this.oImgAfter = document.createElement('img');
this.oImgAfter.src = this.oImgSource[1].src;
this.oImgAfter.style.top = '0px';
this.oImgAfter.style.left = '0px';
this.oImgAfter.style.width = this.iPanWidth + 'px';
this.oImgAfter.style.height = this.iPanHeight + 'px';
this.oImgAfter.style.filter = 'alpha(opacity=0)';
this.oImgAfter.style.opacity = 1;
this.oPan.appendChild(this.oImgAfter);
setInterval(insp.run, this.iTimeInterval);
},


// функция способа изменения
changemode : function(){
this.iMode = (this.iMode == 2) ? 1 : 2;
},


// главная функция рисования петли
run : function(){
if (insp.iMaxZoom > insp.iZStep++) {
if (insp.bHZoom)
{
insp.oImgBefore.style.left = (parseInt
(insp.oImgBefore.style.left) - 1) + 'px';
insp.oImgBefore.style.width = (parseInt
(insp.oImgBefore.style.width) + 2) + 'px';
if (insp.iMode == 2)
{
insp.oImgAfter.style.left = (parseInt
(insp.oImgAfter.style.left) - 1) + 'px';
insp.oImgAfter.style.width = (parseInt
(insp.oImgAfter.style.width) + 2) + 'px';
}
}
if (insp.bVZoom)
{
insp.oImgBefore.style.top = (parseInt
(insp.oImgBefore.style.top) - 1) + 'px';
insp.oImgBefore.style.height = (parseInt
(insp.oImgBefore.style.height) + 2) + 'px';
if (insp.iMode == 2)
{
insp.oImgAfter.style.top = (parseInt
(insp.oImgAfter.style.top) - 1) + 'px';
insp.oImgAfter.style.height = (parseInt
(insp.oImgAfter.style.height) + 2) + 'px';
}
}
if (insp.oImgAfter.filters)
insp.oImgAfter.filters.item(0).opacity =
Math.round(insp.iZStep / insp.iMaxZoom * 100);
else
insp.oImgAfter.style.opacity = insp.iZStep
 / insp.iMaxZoom;
}
else
{
insp.iZStep = 0;
if (insp.bHZoom)
{
if (insp.iMode == 2)
{
insp.oImgAfter.style.left = '0px';
insp.oImgAfter.style.width = insp.iPanWidth + 'px';
}
insp.oImgBefore.style.left = (insp.iMode == 2 ? -
insp.iMaxZoom : 0) + 'px';
insp.oImgBefore.style.width = (insp.iMode == 2 ?
(insp.iPanWidth + (2 * insp.iMaxZoom)) : insp.iPanWidth)
+ 'px';
}
if (insp.bVZoom)
{
if (insp.iMode == 2)
{
insp.oImgAfter.style.top = '0px';
insp.oImgAfter.style.height = insp.iPanHeight + 'px';
}
insp.oImgBefore.style.top = (insp.iMode == 2 ? -
insp.iMaxZoom : 0) + 'px';
insp.oImgBefore.style.height = (insp.iMode == 2 ?
(insp.iPanHeight + (2 * insp.iMaxZoom)) : insp.iPanHeight)
+ 'px';
}
if (insp.oImgAfter.filters)
insp.oImgAfter.filters.item(0).opacity = 0;
else
insp.oImgAfter.style.opacity = 0;
insp.oImgBefore.src = insp.oImgAfter.src;
insp.oImgAfter.src = insp.oImgSource[++insp.iImgStep %
insp.oImgSource.length].src;
}
}
}

 
// загрузка страницы
onload = function()
{
insp.init(); // выполнение инициализации
document.getElementById('mode').onclick =
function(){ // обработка события
insp.changemode();
}
}

 

 

Шаг второй. Файл style.css.

 

Чтобы изображения были на всю ширину экрана установите width и height: 100%

 

 

/*Параметры фона*/

#imgsource
{
display:none;
}

#panel {
position:absolute;
width: 640px;
height: 480px;
overflow: hidden;
opacity: 1;
/* - Тени краёв галереи (можно удалить) - */
-o-box-shadow:0px 0px 7px rgba(0,0,0,0.2),
0px 0px 0px 1px rgba(188,188,188,0.1);
box-shadow:0px 0px 7px rgba(0,0,0,0.2),
0px 0px 0px 1px rgba(188,188,188,0.1);
/* - Округление краёв галереи (можно удалить) - */
border-radius: 8px;
-webkit-border-radius: 8px;
-o-border-radius: 8px;
-ms-border-radius: 8px;
/* - Если удалите тени это тоже удаляйте - */
-webkit-transition:box-shadow 0.3s ease-in-out;
-moz-transition:box-shadow 0.3s ease-in-out;
-o-transition:box-shadow 0.3s ease-in-out;
transition:box-shadow 0.3s ease-in-out;
}
/* - Если удалите тени это тоже удаляйте - */
#panel:hover {
-o-box-shadow:0px 0px 9px rgba(0,0,0,0.4),
0px 0px 0px 1px rgba(188,188,188,0.1);
box-shadow:0px 0px 9px rgba(0,0,0,0.4),
0px 0px 0px 1px rgba(188,188,188,0.1);
}
#panel img {
position: absolute;
-ms-interpolation-mode:nearest-neighbor;
image-rendering: optimizeSpeed;
}

 

 

Шаг третий. Файл index.php.

 

Для начала, прикрепляем файл fon.js и файл стилей style.css.

 

<link rel="stylesheet" type="text/css" href="style.css"/>
<script type="text/javascript" src="fon.js"> </script>

 

Вставляем скрипт в любое место, необязательно между тегами body или head, можно и вынести, главное установите и подберите правильно процент прозрачности opacity

 

<div id="panel">
<div id="imgsource">
<img src="1.jpg"/>
<img src="2.jpg"/>
</div>
</div>

 

Вот такой у нас с вами получился скрипт, который надеюсь Вам пригодится. Спасибо всем за внимание удачи!