Responsywna strona z menu Off-Canvas — kodowanie

Wojciech Parys
Wojtek1150.
Published in
9 min readSep 9, 2014

W ostatnim poradniku zajmowaliśmy się projektem naszej małej responsywnej strony z menu Off-Canvas. W dzisiejszym poradniku zajmiemy się wdrażaniem naszego projektu w życie. Wykorzystamy do tego znany i lubiany przez miliony framework Twitter Bootstrap. Serdecznie zapraszam.

Co nam będzie potrzebne?

Czym będziemy się zajmować:

[demo url=”http://demo.wojtek1150.com/ArcticLapland/"]DEMO[/demo]

Ok, skoro już wszystko wiemy, możemy przystąpić do działania. Zacznijmy od wklepania bazowej struktury strony, oraz załączenia skryptów i plików styli.

<!DOCTYPE html>
<html lang="pl" class="no-js">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="How to create Bootstrap Off Canvas Menu :: Wojtek1150.pl " />
<meta name="keywords" content="bootstrap, offcanvas menu" />
<meta name="author" content="Wojtek1150" />
<link rel="shortcut icon" href="../favicon.ico">
<title>Off Canvas Menu :: Wojtek1150.pl </title><link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://necolas.github.io/normalize.css/3.0.1/normalize.css">
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/main.css">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<!-- BEGIN SCRIPTS -->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<!-- END SCRIPTS -->
</body>
</html>

Tej części, chyba nie trzeba wyjaśniać. Oczywiście znaczniki meta do dowolnej edycji :) Następnym krokiem będzie zamknięcie całej treści na stronie w kontenerze. Ponieważ, po otwarciu menu, przesunie się cała strona. Tworzymy naszego diva i nadajemy mu klasę row-offcanvas oraz drugą pomocniczą: row-offcanvas-left, do której przypiszemy przesunięcie treści. Dzięki takiemu zabiegowi nie będziemy musieli się powtarzać w kodzie, oraz będziemy mieli możliwość prostego wyboru, z której strony ma nasze menu się pojawiać, ale o tym troszeczkę później :)
Zajmijmy się teraz topem naszej strony, czyli znacznikiem header. Nie musimy się długo zastanawiać, co nam tam będzie potrzebne, gdyż mamy projekt. Dla tych, co pominęli poprzednią lekcję, przypominam - logotyp, menu, przycisk otwierania oraz przycisk do zamykania menu. Przycisk zamykania moglibyśmy sobie darować, gdyż menu będzie zajmować 70% szerokości strony, więc potencjalny użytkownik da radę kliknąć w przycisk menu, ale tak będzie estetycznej. Zatem ni<header>
<div class="container">
<div class="pull-left visible-xs">
<div id="toggle-menu" data-toggle="offcanvas">Toggle Menu</div>
</div>
<p class="title">Through Arctic Lapland</p>
<nav class="sidebar-offcanvas" id="menu" role="navigation">
<div class="visible-xs">
<div id="close-menu" data-toggle="offcanvas">Close Menu</div>
</div>
<ul>
<li class="active"><a href="#">Home</a></li>
<li><a href="#">About Author</a></li>
<li><a href="#">Read Book</a></li>
<li><a href="#">Buy Book</a></li>
<li><a href="#">Contact</a></li>
<li class="w"><a href="http://wojtek1150.com" title="Go back to Tutorial">Tutorial</a></li>
</ul>
</nav>
</div>
</header>
Nie jest to zbyt skomplikowany kod. W sekcji header utworzyliśmy kontener o klasie container aby zamknąć całość w gridzie Bootstrapa następnie dodaliśmy przycisk menu, później logotyp. Przycisk zamykania umieściłem w znaczniku nav, aby był tam, gdzie powinien, a nie skakał nam po całym headerze.Teraz najprostsza część, czyli treści na stronie. Posłużyłem się tu zwykły znacznikiem article z klasą container aby zamknąć się w gridzie. A następnie zwykłe znaczniki HTML. Tytuł w H1, data i język w znaczniku p z klasą subline, nazwy kolejnych działów w h2 i h3 dla opisów. Treść w standardowym <p></p> więc tu nie ma zbyt wielkiej filozofii. Oto cały kod:<article class="container">
<h1>Through Arctic Lapland by Cutcliffe Hyne</h1>
<p class="subline">Release Date: June 2, 2014. Language: English</p>
<h2>Preface</h2>
<p>It seems customary in a book of travel to make frequent allusions to other voyagers who have journeyed over the same ground,
or at least the same district, and to make constant references to them, and give copious quotations from their works.
Of course we ought to have gone to the British Museum before starting on our travel, and there read up all books which in the least
bore upon the country which we were going to visit. We omitted to do this, firstly, because we preferred to observe things for ourselves,
from our own individual standpoint, unprejudiced by the way in which other people had observed them; and, secondly,
from the far more potent reason that we made our actual start in a great hurry, and had little enough time for any preparations whatever.</p>
<p>However, on our return to England we thought well to check the information we had garnered. So we duly provided ourselves with readers’
tickets for[viii] that institution, and went to the British Museum Library, and got down every book which seemed in any way to bear upon the
country we had wandered over, regardless of the tongue in which it was written. It was a surprise to us to learn (and may we add that the
surprise was not without its pleasant savour?) that of all the volumes in that collection not one covered the route which we took during
summer through Arctic Lapland. Many had gone near it, from a gentleman of bygone date who wrote in Latin, to Mr. Paul du Chaillu, who chats
about the larger part of the Scandinavian Peninsula. But we seemed to have stumbled across the one bit of Europe which has not been pilloried
on paper at one time or another, and so we here venture to take up a couple of note-books which were originally made for personal gratification,
and amplify them into a volume of letterpress and sketches which may haply interest others.</p>
<h2>CHAPTER I</h2>
<h3>LONDON TO VARDÖ, WITH A FEW EXAMPLES OF HOW PLANS MAY BE CHANGED</h3>
<p>The wharves of Katherine Dock were black with many thousands of people, and all their eyes converged on a little auxiliary barque which
was working out of the basin under her own gentle steam. The barque carried a white tub at her mainmast-head, was rigged with single topsails,
bore many white double-ended boats upturned on skids amidships, and was decorated with sundry other matters which even to the shore eye would
seem strange in London river. Stacked in her waist were bags of coal, crates, packing cases, a couple of ice-anchors, a tangle of trellis-work sledges,
and other quaint trifles which had not yet been struck below.</p>
<p>Any craft more unlike the ordinary conventional type of yacht it would have been hard to conceive, and yet the burgee of the Royal Thames Yacht
Club fluttered out from above the white crow’s nest (or fouled the telescope rail, as the case might be) and an[2] English blue ensign hung clean
and unfrayed from the mizzen truck, as the mizzen gaff, its more orthodox station, had not yet been set up.</p>
<p>The barque was already a vessel well known. As a sealer and whale-fisher she had earned fat dividends for Dundee owners; as the S.Y.
Windward she had made history, and helped to found the British colony of Elmwood in Franz Josef’s Land, and had been iced up for an Arctic winter
in a bay at the back of Cape Flora; and on this trip she was destined (although no one even guessed at it then) to acquire a far more international fame.
She was setting out then from Katherine Dock under the command of that old ice-sailor, Captain James Brown, to carry recruits and supplies to the
Jackson-Harmsworth exploring expedition after their second winter amongst the polar ice; and she landed these on the sterile rocks of Franz Josef’s
Land after a bitter struggle with the floes, and brought back with her to the land of champagne and telegraph wires, Frithjof Nansen, the Norskman,
as by this time all the world most thoroughly knows.</p>
<p>Slowly that single-topsail barque was warped across the dock basin, a strange small creature amongst the huge steam shipping;
slowly she passed through the outer lock; and then the ebb of the muddy river took her, and she moved out into the stream, and the black crowds on the dock-head sent up thunderous cheers.</p>
<p>The little auxiliary propeller fluttered astern, and she dropped down river at no ostentatious speed. But the white barrel perched up there under
the main truck betrayed her always, and every vessel of every nationality in those cosmopolitan reaches knew her as the yacht of the English Arctic expedition.
The blue ensign was kept on a constant dance up and down from her mizzen truck, as it answered other bunting, which was dipped in salute from countless
peaks and poop-staffs. Some crews cheered her as she passed at her puny gait through the crowded shipping; the band of the Worcester played her down the
river out of earshot; everybody she passed warmed to her enterprise and wished her success and a snug return.</p>
<p>Ladies, and owner, and shore folk, had come down the river to give her a final “send off,” but these left at Greenhythe with the mud pilot,
and from that began an easy voyage to the rim of the Polar Sea. The Windward was to go North as much as possible under her own canvas; but as some
steam would certainly be required for head winds and other emergencies, she was to call in at Vardö at the entrance to the White Sea to rebunker,
so as to have the largest possible supply of good Welsh steam coal for her final battle with the Northern ice. To this port, in the north-easternmost angle of Arctic Norway,
the Windward carried as passengers Mr. Cecil Hayter, who drew pictures for this book, and another man, who wrote it.</p>
<p>Now, to say that we two had a vague notion of what was ahead of us was putting the matter mildly. We knew many of those concerned in the Jackson-Harmsworth expedition,
and had always had an interest in the achievements of the Windward; and one night in somebody’s billiard-room we had talked vaguely over “going North and doing something up there”
ourselves. We imagined this something might be to explore the Petchora or one of the lesser-known Northern Siberian rivers, to make the acquaintance
of the Samoyede in his native choom, and incidentally to do some big game shooting. We knew remarkably little about the country, and so were quite unfettered
in making some very appetising plans. This was six months before the Windward sailed, and though we met two or three times in the interval,
the matter was only mentioned casually, and with merely a dilettante interest.</p>
<p class="text-center">[...]</p></article><!--/ARTICLE-->
Na koniec stopka:
<footer>
<div class="container">
<span>Copyright &copy; Through Arctic Lapland, 2014</span>
<span class="by">Design by <a href="http://wojtek1150.com" title="Projektowanie stron">Wojtek1150.pl</a></span>
</div>
</footer>
Szkielet naszej strony gotowy. Przystąpmy do kodu CSS, aby nadać jej trochę stylu :)Zaczynamy od ostylowania podstawowych znaczników. Nie będę się tu rozpisywać na tematy dlaczego kolor taki i taki, bo pracujemy zgodnie z projektem. Tak wiec podstawowy CSS:html,body {
overflow-x: hidden;
font-family:'Open Sans', sans-serif;
font-size:16px;
color:#000;
}
header {
background:#222222;
text-align:center;
color:#FFF;
}
p.title{
font-size:2.250em;
font-weight:bold;
margin:0.9em 0 1em;
}
nav ul{
padding:0;
list-style:none;
}
nav ul li{
margin:0;padding:0;
display:inline-block;
border-right:1px solid #444;
}
nav ul li:last-child{
border-right:none;
}
nav ul li a{
color:#aaaaaa;
font-size:1em;
padding:0 15px;
transition:all .3s ease;
}
nav ul li a:hover,
nav ul li.active a{
color:#FFF;
text-decoration:none;
}
nav ul li.w a{
color:#1D8DFA;
font-weight:bold;
}
article{
padding-top:50px;
padding-bottom:50px;
}
h1{
font-weight:bold;
text-align:center;
font-size:2.5em;
}
p.subline{
font-size:0.875em;
text-align:center;
margin-bottom:4em;
}
h2{
font-size:1.500em;
font-weight:bold;
text-align:center;
margin-top:2em;
}
h3{
font-size:1.125em;
font-weight:bold;
text-align:center;
margin:0 0 1em;
}
p:not(.title){
font-size:1em;
text-indent: 2em;
margin-bottom:2em;
}
footer {
background:#222222;
color:#FFF;
line-height:50px;
font-size:0.875em;
}
footer a,
footer a:hover{
color:#FFF;
}
footer span.by{
float:right;
}
Teraz wersja mobilna, którą będziemy aktywować od 768px w dół. Tak więc:@media screen and (max-width: 767px) {html,body{
font-size:14px;
}
p.title{
margin:0;
line-height:70px;
}
#toggle-menu{
position:relative;
padding:0;margin:0 10px 0 0;
height:70px;width:28px;
text-indent:-9999px;
background:url('../img/menu.png') no-repeat left center;
}
#close-menu{
position:relative;
display:block;
padding:0;padding:0;
height:70px;width:100%;
text-indent:-9999px;
border-bottom:1px solid #444;
background:url('../img/close.png') no-repeat left 15px center;
}
h1{
font-size:2em;
}
p.title{
font-size:1.5em;
}
}

Pozostała najważniejsza część, czyli kod odpowiedzialny za przesunięcia i animacje. Wsadźmy to w sekcji z kodem mobilnym, bo nie potrzebujemy tego kodu na PC'tach. Najpierw ustawmy pozycję relatywną dla naszego głównego kontenera, abyśmy mogli nim poruszać. Dodajmy od razu animację dla każdej tranzycji na powiedzmy 250milisekund:
.row-offcanvas {
position: relative;
-webkit-transition: all .25s ease-out;
-o-transition: all .25s ease-out;
transition: all .25s ease-out;
}
Teraz zgodnie z tym, co zdążyłeś zauważyć na początku, zrobimy 2 efekty przejścia, z prawej i z lewej, abyśmy mogli mieć kaprys na zmianę pozycji menu, oraz aby pokazać Ci, że da się to zrobić z obu stron :) Zaczynamy od ustawienia wartości początkowych, ponieważ bez nich nasza animacja nie będzie działać. Następnie ustawiamy nasze menu za ekranem. Menu będzie miało szerokość 70%, więc wklepujemy wartości przeciwne dla prawej i lewej strony.:.row-offcanvas-right {
right: 0;
}
.row-offcanvas-left {
left: 0;
}
.row-offcanvas-right .sidebar-offcanvas {
right: -70%;
}
.row-offcanvas-left .sidebar-offcanvas {
left: -70%;
}
Teraz wartości dodatnie, dla aktywnych elementów - prawda, że proste?.row-offcanvas-right.active {
right: 70%;
}
.row-offcanvas-left.active {
left: 70%;
}
Na sam koniec troszkę CSS'a dla naszego menu, oraz ustawienie mu wysokości. Zmieńmy też pozycje menu na wyświetlanie blokowe z poziomą linią pod każdym elementem:.sidebar-offcanvas {
position: absolute;
top: 0;
height:100%;
width: 70%;
background:#1D1D1D;
}
.sidebar-offcanvas ul li{
border-right:none;
display:block;
line-height:45px;
border-bottom:1px solid #444444;
}
Nasza strona już wygląda jak należy, jest w pełni responsywna, ale nasze menu nadal się nie otwiera i nie zamyka. Przyszła wiec pora na trochę magi w postaci 5 liniowego kodu JavaScript :)$(document).ready(function () {
$('[data-toggle="offcanvas"]').click(function () {
$('.row-offcanvas').toggleClass('active')
});
});
Słowem wyjaśnienia: Gdy dokument zostanie wczytany wywołujemy proste zdarzenie click() odwołując się do każdego elementu z atrybutem data-toggle="offcanvas". Gdy element zostanie kliknięty zostaje wywołana metoda toggleClass(), która nada lub usunie naszemu głównemu kontenerowy klasę active, resztę już załatwia napisany przed chwilą kod CSS.Dla tych co nie mają jak wyciągnąć obrazków do otwarcia i zamknięcia menu, poniżej wrzucam te pliczki jak i źródło całej strony. Do usłyszenia w komentarzach i kolejnym artykule :)[wpdm_file id=13][wpdm_file id=14][wpdm_file id=12]

--

--