<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Очередной блог фрилансера &#187; drag-and-drop</title>
	<atom:link href="http://dreamhelg.ru/tag/drag-and-drop/feed/" rel="self" type="application/rss+xml" />
	<link>http://dreamhelg.ru</link>
	<description>о моей работе в сети и не только</description>
	<lastBuildDate>Fri, 23 Dec 2011 07:10:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Фантастическая CSS3 лайтбокс галерея с помощью jQuery</title>
		<link>http://dreamhelg.ru/2009/12/fancy-lightbox-css3-image-gallery-with-jquery/</link>
		<comments>http://dreamhelg.ru/2009/12/fancy-lightbox-css3-image-gallery-with-jquery/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 11:31:42 +0000</pubDate>
		<dc:creator>dreamhelg</dc:creator>
				<category><![CDATA[верстка]]></category>
		<category><![CDATA[переводы]]></category>
		<category><![CDATA[css3]]></category>
		<category><![CDATA[drag-and-drop]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://dreamhelg.ru/?p=1789</guid>
		<description><![CDATA[<p><img width="200" height="200" src="http://dreamhelg.ru/wp-content/uploads/2009/12/home.png" class="attachment-200x200 wp-post-image" alt="home" title="home" /></p>С удовольствием принимаю эстафету по обзору полезных зарубежных ресурсов, предложенную блоггером <a href="http://cuprum.name/">cuprum</a>, и сегодня, хочу представить вашему вниманию англоязычный блог - <a href="http://tutorialzine.com">tutorialzine.com</a>. Этот блог отличается от других, главным образом тем, что в нем регулярно публикуются очень красивые, а главное полезные, готовые решения для веб-разработчика. И сегодняшняя статья – не исключение.<span id="more-1789"></span>

В сегодняшней статье, мы создадим отличную фото-галерею, которая использует новейшие техники <strong>CSS3</strong> и <strong>Jquery</strong>. Созданный нами скрипт, будет сканировать папку с картинками на вашем веб-сервере, и строить на основе полученных данных полноценную drag-and-drop галерею.

Это решение будет SEO-дружелюбным, кроме того оно будет работать даже с браузерами, выпущенными в одно время с IE6 (за исключением потери нескольких красивых эффектов).

Мы будем использовать <strong>jQuery</strong>, <strong>jQuery UI</strong> (для реализации drag-and-drop) и плагин jQuery <a href="http://fancybox.net/">fancybox</a> в дополнение к PHP и CSS, для интерактивности и стилизации.

Прежде чем мы начнем, взгляните на конечный <a href="http://demo.tutorialzine.com/2009/11/hovering-gallery-css3-jquery/demo.php">результат</a>.

Итак, давайте перейдем к первому шагу.
<h3>Шаг 1 – XHTML</h3>
Основная идея в том, чтобы использовать PHP для генерации необходимой XHTML-разметки для каждого  изображения. Сгенерированный код, в дальнейшем будет включен в файл demo.php.

<strong>demo.php</strong>

[html]
&lt;!-- The gallery container: --&gt;
&lt;div id=&quot;gallery&quot;&gt;

&lt;?php
/* PHP code, covered in detail in step 3 */
?&gt;

&lt;!-- The droppable share box --&gt;
&lt;div class=&quot;drop-box&quot;&gt;
&lt;/div&gt;

&lt;/div&gt;

&lt;div class=&quot;clear&quot;&gt;&lt;/div&gt;

&lt;!-- This is later converted to the modal window with the url of the image: --&gt;
&lt;div id=&quot;modal&quot; title=&quot;Share this picture&quot;&gt;
&lt;form&gt;
&lt;fieldset&gt;
&lt;label for=&quot;name&quot;&gt;URL of the image&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;url&quot; id=&quot;url&quot; class=&quot;text ui-widget-content ui-corner-all&quot; onfocus=&quot;this.select()&quot; /&gt;
&lt;/fieldset&gt;
&lt;/form&gt;

&lt;/div&gt;
[/html]

Здесь нет ничего сложного. Обратите внимание на блок с <code>id =”modal” </code> - он используется для создания модального окна, которое отображается, если пользователь перетаскивает изображение на блок "drop to share". Но подробнее об этом, мы поговорим позже.

<a href="http://dreamhelg.ru/wp-content/uploads/2009/12/i12.jpg"><img class="aligncenter size-full wp-image-1795" title="i12" src="http://dreamhelg.ru/wp-content/uploads/2009/12/i12.jpg" alt="" width="600" height="460" /></a>

<h3>Шаг 2 – CSS</h3>
Теперь, когда у нас есть вся необходимая разметка, пришло время ее стилизовать. Сначала, нам нужно включить CSS-файлы в секции <code>head</code> нашей страницы.

<strong>demo.php</strong>

[html]
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;demo.css&quot; /&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-darkness/jquery-ui.css&quot; type=&quot;text/css&quot; media=&quot;all&quot; /&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;fancybox/jquery.fancybox-1.2.6.css&quot;&gt;
[/html]

После этого, можно перейти к написанию стилей.

<strong>demo.css</strong>

[css]
body{
	/* Styling the body */
	color:white;
	font-size:13px;
	background: #222222;
	font-family:Arial, Helvetica, sans-serif;
}

#gallery{
	/* The pics container */
	width:100%;
	height:580px;
	position:relative;
}

.pic, .pic a{
	/* Each picture and the hyperlink inside it */
	width:100px;
	height:100px;
	overflow:hidden;
}

.pic{
	/* Styles specific to the pic class */
	position:absolute;
	border:5px solid #EEEEEE;
	border-bottom:18px solid #eeeeee;

	/* CSS3 Box Shadow */
	-moz-box-shadow:2px 2px 3px #333333;
	-webkit-box-shadow:2px 2px 3px #333333;
	box-shadow:2px 2px 3px #333333;
}

.pic a{
	/* Specific styles for the hyperlinks */
	text-indent:-999px;
	display:block;
	/* Setting display to block enables advanced styling for links */
}

.drop-box{
	/* The share box */
	width:240px;
	height:130px;
	position:absolute;
	bottom:0;
	right:0;
	z-index:-1;

	background:url(img/drop_box.png) no-repeat;
}

.drop-box.active{
	/* The active style is in effect when there is a pic hovering above the box */
	background-position:bottom left;
}

label, input{
	/* The modal dialog URL field */
	display:block;
	padding:3px;
}

label{
	font-size:10px;
}

fieldset{
	border:0;
	margin-top:10px;
}

#url{
	/* The URL field */
	width:240px;
}
[/css]

Один из представленных выше классов нуждается в пояснении, это CSS-класс <code>pic</code>. Он используется для того картинки выглядели как полароидные снимки. Для достижения такого эффекта, каждому изображению добавляется белая рамка.

Кроме того, в этом классе используется CSS3-свойство <code>box-shadow</code>, благодаря которому, каждый снимок отбрасывает тень.

Если вы посмотрите на демо-страницу, то увидите, что фотографии разбросаны по страницы и развернуты в разные стороны. Такой эффект достигается с помощью CSS, на стороне PHP, как вы скоро увидите.

Остальные стили очень простые, и не нуждаются в детальном объяснении.

<a href="http://dreamhelg.ru/wp-content/uploads/2009/12/images.png"><img class="aligncenter size-full wp-image-1796" title="images" src="http://dreamhelg.ru/wp-content/uploads/2009/12/images.png" alt="" width="600" height="230" /></a>

<h3>Шаг 3 – PHP</h3>
Как вы помните, на шаге 1, мы рассмотрели часть XHTML-разметки, и отметили, что PHP будет использоваться для создания специальной разметки, для каждого изображения. И вот как это делается:

<strong>demo.php</strong>

[php]
/* Configuration Start */
$thumb_directory = 'img/thumbs';
$orig_directory = 'img/original';
$stage_width=600;
$stage_height=400;
/* Configuration end */

$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;

/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = @opendir($thumb_directory) or die(&quot;There is an error with your image directory!&quot;);
$i=1;

while ($file = readdir($dir_handle))
{
	/* Skipping the system files: */
	if($file=='.' || $file == '..') continue;

	$file_parts = explode('.',$file);
	$ext = strtolower(array_pop($file_parts));

	/* Using the file name (withouth the extension) as a image title: */
	$title = implode('.',$file_parts);
	$title = htmlspecialchars($title);

	/* If the file extension is allowed: */
	if(in_array($ext,$allowed_types))
	{
		/* Generating random values for the position and rotation: */
		$left=rand(0,$stage_width);
		$top=rand(0,400);
		$rot = rand(-40,40);

		if($top&gt;$stage_height-130 &amp;&amp; $left &gt; $stage_width-230)
		{
			/* Prevent the images from hiding the drop box */
			$top-=120+130;
			$left-=230;
		}

		/* Outputting each image: */
		echo '
		&lt;div id=&quot;pic-'.($i++).'&quot; class=&quot;pic&quot; style=&quot;top:'.$top.'px;left:'.$left.'px;background:url('.$thumb_directory.'/'.$file.') no-repeat 50% 50%; -moz-transform:rotate('.$rot.'deg); -webkit-transform:rotate('.$rot.'deg);&quot;&gt;

		&lt;a class=&quot;fancybox&quot; rel=&quot;fncbx&quot; href=&quot;'.$orig_directory.'/'.$file.'&quot; target=&quot;_blank&quot;&gt;'.$title.'&lt;/a&gt;

		&lt;/div&gt;';
	}
}

/* Closing the directory */
closedir($dir_handle);
[/php]

Сначала, мы открываем папку миниатюр с помощью <code>opendir</code> (с помощью модификатора @, мы предотвращаем появление любых возможных проблем, отображаемых пользователю) и проходим циклом по всем картинкам.

В цикле, мы пропускаем файлы, не являющиеся изображениями, и генерируем некоторый XHTML-код для каждого изображения, который выводится непосредственно на экран.

Как уже упоминалось ранее, в части CSS, PHP отвечает за вращение и разброс картинок по странице. Каждое изображение позиционируется по случайным <code>X</code> и <code>Y</code> координатам, и поворачивается в диапазоне от <code>-40</code> до <code>40</code> градусов (для предотвращения переворачивания снимков вверх ногами). Все это генерируется с помощью PHP-функции <code>rand()</code> и включается в качестве CSS-стиля картинки, с помощью атрибута <code>style</code>.

Существуют две папки с картинками, использующиеся галереей – thumbs, в которой содержатся миниатюры картинок, размером 100 х 100 пикселей, и original, которая содержит картинку реального размера. Обратите внимание на важную деталь, изображения в папке thumbnail и original, должны иметь одно и то же имя, иначе галерея будет работать не правильно.

Единственно, что осталось сделать – добавить немного интерактивности.

<h3>Шаг 4 – jQuery</h3>
Итак, у нас на руках отличная CSS-галерея. Но это ничего не значит, если мы не можем перетаскивать понравившиеся картинки по экрану и увеличивать их для более детального просмотра, не так ли?

Пришло время JQuery.

<strong>script.js</strong>

[javascript]
$(document).ready(function(){
	// Executed once all the page elements are loaded
	var preventClick=false;
	$(&quot;.pic a&quot;).bind(&quot;click&quot;,function(e){

		/* This function stops the drag from firing a click event and showing the lightbox */
		if(preventClick)
		{
			e.stopImmediatePropagation();
			e.preventDefault();
		}
	});

	$(&quot;.pic&quot;).draggable({

		/* Converting the images into draggable objects */
		containment: 'parent',
		start: function(e,ui){
			/* This will stop clicks from occuring while dragging */
			preventClick=true;
		},
		stop: function(e, ui) {
			/* Wait for 250 milliseconds before re-enabling the clicks */
			setTimeout(function(){ preventClick=false; }, 250);
		}
	});

	$('.pic').mousedown(function(e){
		/* Executed on image click */
		var maxZ = 0;

		/* Find the max z-index property: */
		$('.pic').each(function(){
			var thisZ = parseInt($(this).css('zIndex'))
			if(thisZ&gt;maxZ) maxZ=thisZ;
		});

		/* Clicks can occur in the picture container (with class pic) and in the link inside it */
		if($(e.target).hasClass(&quot;pic&quot;))
		{
			/* Show the clicked image on top of all the others: */
			$(e.target).css({zIndex:maxZ+1});
		}
		else $(e.target).closest('.pic').css({zIndex:maxZ+1});
	});

	/* Converting all the links to a fancybox gallery */
	$(&quot;a.fancybox&quot;).fancybox({
		zoomSpeedIn: 300,
		zoomSpeedOut: 300,
		overlayShow:false
	});

	/* Converting the share box into a droppable: */
	$('.drop-box').droppable({
		hoverClass: 'active',
		drop:function(event,ui){

			/* Fill the URL text field with the URL of the image. */
			/* The id of the image is appended as a hash #pic-123 */
			$('#url').val(location.href.replace(location.hash,'')+'#' + ui.draggable.attr('id'));
			$('#modal').dialog('open');
		}
	});

	/* Converts the div with id=&quot;modal&quot; into a modal window  */
	$(&quot;#modal&quot;).dialog({
		bgiframe: true,
		modal: true,
		autoOpen:false,

		buttons: {
			Ok: function() {
				$(this).dialog('close');
			}
		}
	});

	if(location.hash.indexOf('#pic-')!=-1)
	{
		/* Checks whether a hash is present in the URL */
		/* and shows the respective image */
		$(location.hash+' a.fancybox').click();
	}
});
[/javascript]

Сначала, мы вешаем, обработчик событий на клик по картинке, с тем, чтобы лайтбокс не срабатывал, когда мы просто перетаскиваем изображение.

После этого, мы делаем все картинки перетаскиваемыми, а затем настраиваем lightbox.

Теперь, нам нужно сделать блок «Drop to share», «принимающим», то есть блок сможет определять, когда к нему подвели и отпустили картинку. Это позволит нам применить специальный стиль к контейнеру, и открыть модальное окно.

Модальное окно – это компонент пользовательского интерфейса, поставляемый вместе с jQuery UI. Он прячет все элементы страницы, под полупрозрачный слой, тем самым блокируя их использование для пользователя. Единственная вещь, полностью привлекающая внимание пользователя – это окно с сообщением, которое в нашем случае, окно содержит URL картинки.

И наконец, у нас есть несколько строк кода, которые проверяют, есть ли строки вида  <code>#pic-123</code> в URL, c помощью которых, лайтбокс показывает соответствующие изображения при загрузке страницы.

Наша CSS3-галерея готова.

<a href="http://demo.tutorialzine.com/2009/11/hovering-gallery-css3-jquery/demo.zip">Скачать архив с примером</a>.

Перевод статьи «<a href="http://tutorialzine.com/2009/11/hovering-gallery-css3-jquery/">An Awesome CSS3 Lightbox Gallery With jQuery</a>», автор <strong>Martin</strong>
<h3><strong> </strong>Другие участники эстафеты:</h3>
<ul>
	<li>Cuprum.name – <a href="http://cuprum.name/page/cvetovaya-model-rgba">Работа с цветовой моделью RGBA</a></li>
	<li>rotorweb.ru — <a href="http://rotorweb.ru/mysli-vslux/saying-goodbye-overflow-hidden.html">Скажем прощай overflow: hidden!</a></li>
</ul>
Хотите принять участие в эстафете? Это очень просто, опубликуйте перевод статьи из представляемого ресурса, сообщите мне, и я с удовольствием поставлю ссылку на ваш блог. Обязательное условие – статьи и ресурсы не должны повторятся.]]></description>
		<wfw:commentRss>http://dreamhelg.ru/2009/12/fancy-lightbox-css3-image-gallery-with-jquery/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

