Красивая галерея на jQuery.
Сегодня мы сделаем простую jQuery галерею, которая будет сканировать папку с изображениями и показывать их в галерее. Мы будем использовать PHP, jQuery, CSS и плагин jQuery — Lightbox.
HTML
Начнем с html разметки:
<div id="container"> <div id="heading"> <!-- заголовок --> <h1>A cool jQuery gallery</h1> </div> <div id="gallery"> <!-- в этом блоке будут содержаться картинки --> <?php //наш php код ?> <div></div> </div> <div id="footer"> <!-- подвал --> </div> </div>
Место для php кода пока пусто, заполним его.
PHP
Задача нашего php кода — просканировать папку с изображениями и вывести их с соответствующим CSS оформлением. Такой подход делает добавление новых изображений в галерею очень простым — просто добавьте их в папку к уже существующим.
<?php
$directory = 'gallery'; //папка с картинками
$allowed_types=array('jpg','jpeg','gif','png'); //допустимые типы
$file_parts=array();
$ext='';
$title='';
$i=0;
//пытаемся открыть папку
$dir_handle = @opendir($directory) or die("There is an error with your image directory!");
while ($file = readdir($dir_handle)) //проходим файлы в папке
{
if($file=='.' || $file == '..') continue; //пропускаем ссылки на текущую и родительскую папки
$file_parts = explode('.',$file); //разбиваем название файла на части отделенные точкой
$ext = strtolower(array_pop($file_parts)); //последний элемент - формат
$title = implode('.',$file_parts);
$title = htmlspecialchars($title);
$nomargin='';
if(in_array($ext,$allowed_types)) //если тип допустим
{
if(($i+1)%4==0) $nomargin='nomargin';
echo '
<div style="background:url('.$directory.'/'.$file.') no-repeat 50% 50%;">
<a href="'.$directory.'/'.$file.'" title="'.$title.'" target="_blank">'.$title.'</a>
</div>';
$i++;
}
}
closedir($dir_handle); //закроем папку
?>
CSS
Мы создали каркас нашей галереи, осталось придать ей красивый вид:
body,h1,h2,h3,p,td,quote,small,form,input,ul,li,ol,label{
margin:0px;
padding:0px;
font-family:Arial, Helvetica, sans-serif;
}
body{
margin-top:20px;
color:white;
font-size:13px;
background-color:#222222;
}
.clear{
clear:both;
}
a, a:visited {
color:#00BBFF;
text-decoration:none;
outline:none;
}
a:hover{
text-decoration:underline;
}
#container{
width:890px;
margin:20px auto;
}
#heading,#footer{
background-color:#2A2A2A;
border:1px solid #444444;
height:20px;
padding:6px 0 25px 15px;
margin-bottom:30px;
overflow:hidden;
}
#footer{
height:10px;
margin:20px 0 20px 0;
padding:6px 0 11px 15px;
}
div.nomargin{
margin-right:0px;
}
.pic{
float:left;
margin:0 15px 15px 0;
border:5px solid white;
width:200px;
height:250px;
}
.pic a{
width:200px;
height:250px;
text-indent:-99999px;
display:block;
}
h1{
font-size:28px;
font-weight:bold;
font-family:"Trebuchet MS",Arial, Helvetica, sans-serif;
}
h2{
font-weight:normal;
font-size:14px;
color:white;
}
jQuery
В нашей галерее мы будем использовать плагин Lightbox, для этого подключим необходимые файлы.
<link rel="stylesheet" type="text/css" href="lightbox/css/jquery.lightbox-0.5.css" /> <link rel="stylesheet" type="text/css" href="demo.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript" src="lightbox/js/jquery.lightbox-0.5.pack.js"></script> <script type="text/javascript" src="script.js"></script>
Код файла script.js:
// после полной загрузки страницы
$(document).ready(function(){
$('.pic a').lightBox({
// мы вызываем метод lightBox и конвертируем все классы .pic в галерею Lightbox
imageLoading: 'lightbox/images/loading.gif',
imageBtnClose: 'lightbox/images/close.gif',
imageBtnPrev: 'lightbox/images/prev.gif',
imageBtnNext: 'lightbox/images/next.gif'
});
});
Наша галерея готова!








Всё красиво здесь, только вот не судьба с кириллицей в названии изображения))
1. Изображеня назвать цифрами (1, 2, 3,4…);
2. Зделать массив названий изображений на кириллице;
3. $title =$array[$title];
4. По детски, но работает))
Благодарю вас за помощь!!! Целый день искал подобное решение))
Приветствую. Красивый строгий предпросмотр, но при выводе отдельной картинки на большом разрешении она смотрится мелкой. Есть ли вариант, чтобы изображения растягивались в зависимости от разрешения монитора?