Сегодня — наша последняя часть нашего «Bottom Menu Builder», который мы начали вчера. Мы собираемся реализовать наши последние функции: Предварительный просмотр и Экспорт (необязательно). Таким образом, веб-мастер сможет упорядочивать ссылки путем перетаскивания, а затем он может нажать кнопку «Предварительный просмотр» для предварительного просмотра (и экспорта результатов). Я переместил все ссылки в отдельный php-файл (и теперь мы можем иметь прямой доступ к этим ссылкам из PHP). В вашем случае это может быть база данных в качестве примера (в случае большого проекта). Итак, начнем..
В качестве первого, я бы предложил вам скачать исходные файлы и держать демонстрацию открытой во вкладке для лучшего понимания.
Live Demo
результат загрузки
Итак, начнем!
Шаг 1. HTML
Сегодня у нас нет статических html-файлов, я переместил содержимое нашего index.html в новый файл index.php.
Шаг 2. CSS
В дополнение к нашему файлу main.css я добавил новый файл CSS (для стилизации нашей страницы предварительного просмотра):
CSS / bmenu.css
/* menu builder styles */
.actions {
border: 1px solid #CCCCCC;
font-size: 24px;
margin: 20px auto 5px;
overflow: hidden;
padding: 10px;
width: 900px;
/* CSS3 Box sizing property */
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
}
.columns {
margin: 0 auto;
overflow: hidden;
width: 900px;
}
.column {
border: 1px dotted #ccc;
float: left;
min-height: 100px;
padding: 10px;
position: relative;
width: 33.3%;
/* CSS3 Box sizing property */
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
}
.column a {
cursor: pointer;
display: block;
font-size: 16px;
height: 30px;
margin-bottom: 5px;
position: relative;
text-align: center;
}
Шаг 3. JS
Пожалуйста, добавьте следующий код в наш файл main.js (внизу, сразу после вызова updateHandlerDrop):
JS / main.js
// preview button
var previewBtn = document.querySelectorAll('#preview');
addEvent(previewBtn, 'click', function (event) {
if (event.preventDefault) event.preventDefault();
var params = '';
var oColumns = document.querySelectorAll('div.column');
for (var i = 0; i < oColumns.length; i++) {
var iCol = i+1;
var sColElems = '';
for (var k = 0; k < oColumns[i].childNodes.length; k++) {
if (oColumns[i].childNodes[k].nodeType == document.ELEMENT_NODE && oColumns[i].childNodes[k].tagName == 'A') {
sColElems += oColumns[i].childNodes[k].id + '_';
}
}
params += iCol + '=' + sColElems + '&';
}
// open results
var http = new XMLHttpRequest();
http.open('POST', 'preview.php', true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.setRequestHeader('Content-length', params.length);
http.setRequestHeader('Connection', 'close');
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
document.open();
document.write(http.responseText);
return;
}
}
http.send(params);
return false;
});
Это код кнопки предварительного просмотра. Как видите, он готовит все необходимые параметры для отправки в наш новый файл preview.php. По сути, это своего рода сериализация наших активных ссылок (в столбцах).
Шаг 4. PHP
Теперь пришло время ознакомиться с нашими сценариями на стороне сервера. Как я уже говорил, я переместил все ссылки в отдельный php-файл (links.php), вот он:
links.php
<?
$aLinks = array(
1 => array('Link 1', '#link1'),
2 => array('Link 2', '#link2'),
3 => array('Link 3', '#link3'),
4 => array('Link 4', '#link4'),
5 => array('Link 5', '#link5'),
6 => array('Link 6', '#link6'),
7 => array('Link 7', '#link7'),
8 => array('Link 8', '#link8'),
9 => array('Link 9', '#link9'),
10 => array('Link 10', '#link10'),
11 => array('Link 11', '#link11'),
12 => array('Link 12', '#link12')
);
Теперь я должен сгенерировать код для нашей индексной страницы (с помощью компоновщика) с использованием этого массива:
index.php
<?php
require_once('links.php'); // include set of all possible links
// prepare draggable elements
$sLinks = '';
foreach ($aLinks as $i => $aPair) {
list($sText, $sUrl) = $aPair;
$sLinks .= '<a id="'.$i.'" draggable="true">'.$sText.'</a>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Bottom Menu Builder (HTML5) - Step 2 (of 2) | Script Tutorials</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header tabindex="0">
<h2>Bottom Menu Builder (HTML5) - Step 2 (of 2)</h2>
<a href="http://www.script-tutorials.com/bottom-menu-builder-html5-2/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
</header>
<div class="actions">
Actions:
<button id="preview">Preview</button>
<button id="add_col">Add Column</button>
</div>
<div class="actions">Columns (with active elements)</div>
<div class="columns">
<div class="column" id="drop_1" droppable="true"><img src="images/delete.png" onclick="removeColumn(this)" /></div>
<div class="column" id="drop_2" droppable="true"><img src="images/delete.png" onclick="removeColumn(this)" /></div>
<div class="column" id="drop_3" droppable="true"><img src="images/delete.png" onclick="removeColumn(this)" /></div>
</div>
<div style="clear:both"></div>
<div class="actions">All (inactive) elements. You can drag these elements into columns.</div>
<div class="inactive" droppable="true">
<?= $sLinks ?>
</div>
<script src="js/main.js"></script>
</body>
</html>
И, наконец, наша страница предварительного просмотра:
preview.php
<?php
require_once('links.php'); // include set of all possible links
$sColumns = '';
$iColCnt = count($_POST); // Columns count
$dWidth = round(100 / $iColCnt, 1); // Column width
foreach ($_POST as $sCol => $sColEls) { // walk through all POST params
$iColId = (int)$sCol; // Column ID
$sColumns .= '<div class="column" style="width:'.$dWidth.'%">';
$aEls = explode('_', $sColEls); // obtain elements in column
if (is_array($aEls) && count($aEls)) {
foreach ($aEls as $iPos => $sEl) { // walk through all elements
$iEl = (int)$sEl;
if ($iEl) {
list($sText, $sUrl) = $aLinks[$iEl];
$sColumns .= '<a href="'.$sUrl.'">'.$sText.'</a>';
}
}
}
$sColumns .= '</div>';
}
// Here you can save current value of $sColumns into some cache file
//file_put_contents('cache/bottom_menu.html', $sColumns);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Bottom Menu Builder (HTML5) - Step 2 (of 2) | Script Tutorials</title>
<link href="css/bmenu.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header tabindex="0">
<h2>Bottom Menu Builder (HTML5) - Step 2 (of 2)</h2>
<a href="http://www.script-tutorials.com/bottom-menu-builder-html5-2/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
</header>
<div class="actions">Result bottom menu (preview)
<a href="index.php" style="float:right">Start again</a>
</div>
<div class="columns">
<?= $sColumns /*and finally - draw our result menu*/ ?>
</div>
</body>
</html>
Небольшой код вверху — подготовка результирующего нижнего меню (с колонками). Как вы можете видеть, вы даже можете раскомментировать ‘file_put_contents’, чтобы сгенерировать кеш-файл меню результатов.
Live Demo
результат загрузки
Вывод
Вот и все, я надеюсь, что мы создали действительно удобный для пользователя скрипт — построитель меню html5 drag and drop. Надеюсь, что наш учебник помог вам. Не стесняйтесь делиться нашими уроками с друзьями. Удачи!