Ако не съм ви го казвал досега - обичам простичките неща. Защо? Защото, колкото по-просто е направено дадено нещо, то вероятността да се развали/счупи/спре да работи е по-малка. Другата причина е, че обикновено сложните неща са съставени от прости, т.е. за да схванете логиката трябва да се почне от А и Б. Днешният урок е типичен пример за това как с един наглед простичък метод, може да се постигне доста приятен краен резултат.
Както всички добре знаем, без HTML нищо от това, което четете в момена няма да бъде реалност. Всичко от най-семплия до най-препълнения с модерни технологии сайт е зависимо от HTML. "Бащата" на езика, британският физик Тим Бърнърс-Лий, днес е директор на консорциума W3C. По времето, когато е работил в ЦЕРН той е получил задача да улесни работата на своите колеги, като измисли по-лесен начин за достъп и обработка на информацията от провеждащите се научни изследвания. Един вид трябвало им страхотна документация, за да извличат максимума от работата си. Така се ражда и HTML, който първоначално имал доста ограничени възможности, но заради лесната употреба и възможността да бъде четен от множество потребители той свършил прекрасна работа.
И след този кратък урок по история предполагам вече сте се досетили, че днес ще си говорим за това как да направим една документация, една книга или защо не един цял сайт по-удобен за навигиране.
Надявам се на всички е ясно, че връзките чрез <a href="#"> могат да водят не само извън документа, но и до определени части от него. Сигурен съм, че доста често, разглеждайки страница сте попадали на бутони, които ви препращат на конкретна част от нея, за да няма излишно лутане от страна на потребителя. Много популярно е и бутончето "Back to top", което след края на текста ви връща в най-горната част на страницата, за да продължите с навигирането. Този тип връзки се ползват и из форумите, като с тях може да вземете линк за даден пост и да го препратите на приятел вместо да му дадете линк към цялата страница и да му кажете "Пост 56, а сега брой!". Разбира се, постовете имат и номерация, така че това е в кръга на шегата. Все пак схванахте ми идеята - този тип връзки са много полезни и с малко по-креативно мислене могат да се постигнат чудеса. Разбира се, в нашия пример аз ще се придържам към простичките неща и съм ви подготвил класическа HTML статия с кратко съдържание, което се явява навигация. Ако някой се е почувствал авторски засегнат, статията за примера е взета от Wikipedia.
| View DemoDownload |
Каква е идеята?
Всъщност отново ще използвам ключовата дума за тази статия и ще кажа, че всъщност в същината си идеята е много проста. Първият и най-важен ефект, който искаме да постигнем тук е много по-удобна навигация из документа. Обикновено, когато цъкнете на някоя от вътрешните връзки, браузърът мигновено ви изстрелва в крайна позиция без да ви става много ясно къде се намирате. Първата реакция е да погледнете скрола отстрани, но това не е особено добър ориентир, особено при по-дългите документи. Тук идва и решението. Както виждате на демото, благодарение на плавната анимация, добивате представа в коя част от документа сте, дали следващия пасаж, който искате да прочетете е преди или след настоящия и т.н. Вторият бонус, който получавате с този ефект е чисто визуалната наслада, която се слага, за да гъделичка нуждите на капризните потребители. Като трети бенефит бих изтъкнал безбройните ситуации, в които този метод може да се ползва. Мисля, че тези причини са достатъчни, за да му обърнете по-сериозно внимание.
Как работи всичко?
По-надолу може да видите целия HTML, но засега съм го скрил, тъй като е прекалено голям, а на нас ни трябват само конкретни части от него. В примера, който съм дал виждате, че навигацията е изградена от списък с линкове към заглавията на статията. Самата навигация е фиксирана спрямо прозореца ви и това определено помага в случая. Между другото това фиксиране не работи под Internet Explorer 6, така че може би е време да смените браузъра.
<div id="nav"> <ul> <li>Table of Contents</li> <li><a href="#whatis">What the hell is that?</a></li> <li><a href="#history">History</a></li> <li><a href="#beliefs">Beliefs</a></li> <li><a href="#significance">Significance</a></li> </ul> </div>
От друга страна ето как изглежда и един пасаж от статията.
<h2 id="whatis">What the hell is that?</h2> <p>The Flying Spaghetti Monster (FSM) is the deity of the parody religion the Church of the Flying Spaghetti Monster or Pastafarianism. Created in 2005 by Oregon State physics graduate Bobby Henderson, it was originally intended as a satirical protest against the decision by the Kansas State Board of Education to require the teaching of intelligent design as an alternative to evolution in public schools. In an open letter sent to the Kansas State Board of Education, Henderson parodied the concept of intelligent design by professing belief in a supernatural creator which closely resembles spaghetti and meatballs. Henderson further called for his "Pastafarian" theory of creation to be allotted equal time in science classrooms alongside intelligent design and evolution. He explained that since the intelligent design movement uses ambiguous references to an unspecified "Intelligent Designer", any conceivable entity may fulfill that role, even a Flying Spaghetti Monster. After Henderson published the letter on his website, it rapidly became an internet phenomenon and a symbol for the case against teaching intelligent design in public schools.</p>
С две думи, линкът от навигацията води до заглавието на пасажа и така приковава вниманието на четящия. Нищо сложно. Ето и пълната версия на HTML-a.
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="css/style.css" type="text/css" /> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="js/jq-nav.js"></script> <title>По-удобна навигация с jQuery</title> </head> <body> <div id="all"> <div id="page"> <div id="nav"> <ul> <li>Table of Contents</li> <li><a href="#whatis">What the hell is that?</a></li> <li><a href="#history">History</a></li> <li><a href="#beliefs">Beliefs</a></li> <li><a href="#significance">Significance</a></li> </ul> </div> <div id="content"> <h1>Flying Spaghetti Monster</h1> <h2 id="whatis">What the hell is that?</h2> <p>The Flying Spaghetti Monster (FSM) is the deity of the parody religion the Church of the Flying Spaghetti Monster or Pastafarianism. Created in 2005 by Oregon State physics graduate Bobby Henderson, it was originally intended as a satirical protest against the decision by the Kansas State Board of Education to require the teaching of intelligent design as an alternative to evolution in public schools. In an open letter sent to the Kansas State Board of Education, Henderson parodied the concept of intelligent design by professing belief in a supernatural creator which closely resembles spaghetti and meatballs. Henderson further called for his "Pastafarian" theory of creation to be allotted equal time in science classrooms alongside intelligent design and evolution. He explained that since the intelligent design movement uses ambiguous references to an unspecified "Intelligent Designer", any conceivable entity may fulfill that role, even a Flying Spaghetti Monster. After Henderson published the letter on his website, it rapidly became an internet phenomenon and a symbol for the case against teaching intelligent design in public schools.</p> <div class="center"><img src="img/Touched_by_His_Noodly_Appendage.jpg" alt="" /></div> <p>Pastafarian beliefs—generally satires of creationism—are presented both on Henderson's website, where he is described as a "prophet", and in The Gospel of the Flying Spaghetti Monster, published by Villiard Press in 2006. The central belief is that an invisible and undetectable Flying Spaghetti Monster created the universe. Pirates are revered as the original Pastafarians, and Pastafarians facetiously assert that a steady decline in the number of pirates has resulted in a significant rise in global temperature. Pastafarians celebrate every Friday as a holy day; this is the holiest of Pastafarian holidays, which include Ramendan, Pastover, and a vaguely defined holiday named "Holiday".</p> <p>On Henderson's website visitors can purchase t-shirts, trinkets, and bumper stickers and share pictures of crafts devoted to the Flying Spaghetti Monster. Such communal activities attracted the attention of three religious scholars, who organized a panel at the 2007 American Academy of Religion meeting to discuss the Flying Spaghetti Monster. Due to its popularity and exposure, the Flying Spaghetti Monster is often used as a modern version of Russell's teapot. While generally praised by the media and endorsed by individual members of the scientific community, the Flying Spaghetti Monster has received criticism from the intelligent design hub Discovery Institute, the ministry Answers in Genesis, and the Southern Baptist Theological Seminary. Self-described Pastafarians spearheaded efforts in Polk County, Florida, to dissuade the local school board from adopting new standards on evolution and have engaged in other disputes.</p> <h2 id="history">History</h2> <p>The first public exposure of the Church of the Flying Spaghetti Monster can be dated to January 2005 when Bobby Henderson, then a 25-year-old Oregon State University physics graduate, sent an open letter regarding the Flying Spaghetti Monster to the Kansas State Board of Education. The letter was sent prior to the Kansas evolution hearings as an argument against the teaching of intelligent design in biology classes. Henderson, describing himself as a "concerned citizen" representing ten million others, stated that both his theory and intelligent design had equal validity.</p> <p>According to Henderson, since the intelligent design movement uses ambiguous references to a designer, any conceivable entity may fulfill that role, including a Flying Spaghetti Monster. Henderson explained, "I don't have a problem with religion. What I have a problem with is religion posing as science. If there is a god and he's intelligent, then I would guess he has a sense of humor."</p> <p>In May, having received no reply from the Kansas State Board of Education, Henderson posted the letter on his website, gaining significant public interest. Shortly thereafter, Pastafarianism became an internet phenomenon. Henderson published the responses he then received from Board members. Three board members, all of whom opposed the curriculum amendments, responded positively; a fourth board member responded with the comment "It is a serious offense to mock God." Henderson has also published the significant amount of hate mail, including death threats, that he has received. Within one year of sending the open letter, Henderson received more than 15,000 emails on the Flying Spaghetti Monster, of which he has said that "about 95 percent have been supportive, while the other five percent have said I am going to hell". During that time, his site garnered more than 350 million hits and used about 700 gigabytes of bandwidth per month.</p> <img src="img/220px-FSM_Logo.svg.png" alt="" class="fleft"/> <p>As word of Henderson's challenge to the Board spread, his website and cause received more attention and support. The satiric nature of Henderson's argument made the Flying Spaghetti Monster popular with bloggers as well as humor and Internet culture websites. The Flying Spaghetti Monster was featured on websites such as Boing Boing, Something Awful, Uncyclopedia, and Fark.com. Moreover, an International Society for Flying Spaghetti Monster Awareness and other fan sites emerged. As public awareness grew, the mainstream media picked up on the phenomenon. The Flying Spaghetti Monster became a symbol for the case against intelligent design in public education. The open letter was printed in many large newspapers, including the The New York Times, The Washington Post, and Chicago Sun-Times, and received "worldwide press attention" according to one journalist. Henderson himself was surprised by its success, stating that he "wrote the letter for [his] own amusement as much as anything".</p> <h2 id="beliefs">Beliefs</h2> <p>Henderson proposed many Pastafarian tenets in reaction to common arguments by proponents of intelligent design. These "canonical beliefs" are presented by Henderson in his letter to the Kansas State Board of Education, the Gospel of the Flying Spaghetti Monster, and on Henderson's web site, where he is described as a prophet. They tend to satirize creationism.</p> <p>The central belief is that an invisible and undetectable Flying Spaghetti Monster created the universe "after drinking heavily". According to these beliefs, the Monster's intoxication was the cause for a flawed Earth. Furthermore, according to Pastafarianism, all "evidence" for evolution was planted by the Flying Spaghetti Monster in an effort to test Pastafarians' faith—parodying certain biblical literalists. When scientific measurements such as radiocarbon dating are taken, the Flying Spaghetti Monster "is there changing the results with His Noodly Appendage". The Pastafarian belief of Heaven contains a beer volcano and a stripper factory. The Pastafarian Hell is similar, except that the beer is stale and the strippers have sexually transmitted diseases.</p> <p>Pastafarians' beliefs extend into religious ceremony. Pastafarians celebrate every Friday as a holy day. Prayers are concluded with a final declaration of affirmation, "R'amen"; the term is a parodic portmanteau of the Semitic term "Amen" and the Japanese noodle dish, ramen.</p> <h2 id="significance">Significance</h2> <p>The Church of the Flying Spaghetti Monster now consists of thousands of "followers," primarily concentrated on college campuses and in Europe. According to the Associated Press, Henderson's website has become "a kind of cyber-watercooler for opponents of intelligent design". On it, visitors track meetings of pirate-clad Pastafarians, sell trinkets and bumper stickers, and sample photos that show "visions" of the Flying Spaghetti Monster. In August 2005, the Swedish concept designer Niklas Jansson created an adaptation of Michelangelo's The Creation of Adam, superimposing the Flying Spaghetti Monster over God. This became and remains the Flying Spaghetti Monster's de facto brand image. The Hunger Artists Theatre Company produced a comedy called The Flying Spaghetti Monster Holiday Pageant in December 2006, detailing the history of Pastafarianism. The production has spawned a sequel called Flying Spaghetti Monster Holy Mug of Grog, performed in December 2008. This communal activity attracted the attention of three University of Florida religious scholars, who assembled a panel at the 2007 American Academy of Religion meeting to discuss the Flying Spaghetti Monster.</p> <p>In November 2007, three talks involving the Flying Spaghetti Monster were delivered at the American Academy of Religion's annual meeting in San Diego. The talks, with titles like Holy Pasta and Authentic Sauce: The Flying Spaghetti Monster's Messy Implications for Theorizing Religion, examined the elements necessary for a group to constitute a religion. Speakers inquired whether "an anti-religion like Flying Spaghetti Monsterism [is] actually a religion". They were based on the paper, Evolutionary Controversy and a Side of Pasta: The Flying Spaghetti Monster and the Subversive Function of Religious Parody, published in the GOLEM Journal of Religion and Monsters. The panel garnered an audience of one hundred of the 9,000 conference attendees, and conference organizers received critical e-mails from Christians offended by it.</p> <p>Since October 2008, the local chapter of the Church of the Flying Spaghetti Monster has sponsored an annual convention called Skepticon on the campus of Missouri State University. Atheists and skeptics give speeches on various topics, and a debate with Christian experts is held. Organizers tout the event as the "largest gathering of atheists in the Midwest." On the non-profit microfinancing site, Kiva, the Flying Spaghetti Monster group tops all other "Religious Congregations" in donations. The group's motto is "Thou shalt share, that none may seek without finding". As of 28 January 2010 (2010 -01-28)[update], it has donated more than $190,000 in loans. </p> <span>Цялата статия: <a href="http://en.wikipedia.org/wiki/Flying_Spaghetti_Monster">Wikipedia</a>.</span> </div> </div> </div> </body> </html>
CSS-ът също е маловажен в случая, като не влияе по никакъв начин на крайния резултат. Все пак се постарах да му придам някакъв вид.
CSS
body {
margin: 0;
padding: 0;
font-size: 15px;
font-family: "Trebuchet MS", Arial, Tahoma, Verdana, sans-serif;
line-height: 21px;
background: #fff;
color: #666;
}
h1, h2, h3, h4, h5, h6 { margin: 0; line-height: normal; }
ul { margin: 0; padding: 0; list-style: none; }
a, a:link, a:visited { outline: none; text-decoration: none; color: #0076b9; }
a:hover{ text-decoration: underline; }
p { margin: 0 0 10px; }
.clr { clear: both; height: 0; line-height: 0; font-size: 0; }
.fleft { float: left; }
.center { text-align: center; }
#page {
width: 990px;
margin: 0 auto;
padding: 50px 0;
}
#content {
float: right;
width: 600px;
margin: 0 195px 0 0;
}
#content h1 {
font-size: 30px;
text-align: center;
margin: 0 0 30px;
border: 1px solid #ccc;
padding: 10px 0;
color: #414141;
}
#content h2 {
font-family: Georgia, serif;
font-size: 22px;
font-weight: 400;
color: #6291b8;
padding: 0 0 5px;
border-bottom: 1px solid #ddd;
margin: 20px 0 10px;
}
#content img {
border: 1px solid #bbb;
padding: 5px;
margin: 15px 15px 10px 0;
}
#nav {
position: fixed;
float: left;
width: 144px;
border: 1px solid #ddd;
padding: 14px;
}
#nav li a, #nav li a:link, #nav li a:visited {
color: #0076b9;
}
#nav li a:hover {
color: #0068a3;
}
Shake it!
Стигнахме до най-пипкавата част - jQuery. Тук логиката може малко да ви подведе в търсене на доста по-сложни решения, но всъщност всичко е пред вас. Имаме един вид готова функционалност и от нас се иска само да допълним няколко дребни парченца от пъзела.
Първо е необходимо да изберем подходящия селектор, с който ще филтрираме нашите <а>-та. Аз се спрях на a[href^="#"], тъй като най-много се доближава до това, което искам, но вие може да се пробвате и с други. След това нашата цел е при клик да намерим с кое <h2> си "комуникира" кликнатото <a> и след това да разберем позицията на това h2. За целта търсим href, който да отговаря на същото ID, тъй като реално за да функционират правилно те трябва да са еднакви. Взимаме позицията на елемента с това ID и така показваме къде трябва да застане вертикалният скрол на браузъра. Елементарно, нали? Ето, разгледайте по-обстойно кода ако не ви е станало напълно ясно.
jQuery(document).ready(function () {
$('a[href^="#"]').click(function() {
var aHrefName = $(this).attr('href').substring(1); //Взимаме съдържанието на атрибута href на кликнатия линк и премахваме първия му символ (#). Запазваме остатъка в променлива.
var headingPos = $('#content').find('#' + aHrefName).offset().top; //В документа намираме елемент с ID равно на съдържанието от href атрибута на кликнатия линк, което е заместено от променливата запазена на предния ред. След това взимаме Top позицията на елемента в пространството.
$('html, body').animate({scrollTop: headingPos}, 1000); //Преместваме вертикалния скрол на позиция равна на Top позицията на желания h2. Настройваме и времето, за което това да се случи.
return false; //Спираме стандартното действие на линка, което в случая не променя крайното URL. Това се слага по желание.
});
$('#nav li:first').css('margin-bottom', '5px'); // Извън контекста на примера - добавя margin на първото LI от навигацията, което се води заглавие.
});
Едно малко уточнение за $('html, body') - тук винаги добавяйте и body, тъй като без него WebKit базираните браузъри (Safari/Chrome) не разбират какво се случва.
Урокът стана малко по-дълъг от очакваното, но реших да обърна по-голямо внимание на няколко детайла, които се ползват на доста места и се надявам да сте останали доволни. Съветът ми е да вземете кода и да експериментирате. Може да обърнете внимание и на този plugin, тъй като има сходен принцип на работа, но е една камара код, който в повечето случаи може да не ви е необходим.




Урокът е повече от перфектен, но имам малки проблеми с опитите си да го изпозлвам в форума си.Явно начинаещите не трябва да започват от тук :D
Не би трябвало да имаш проблеми. Скриптът може да се имплементира почти навсякъде и e нужно само да смениш тук-там някое ID :).
В примера съм задал всички линкове, които имат # в себе си да бъдат анимирани - $('a[href^="#"]'). Във форума обаче те са стотици и би подхождало нещо от типа $('#nav a[href^="#"]'), за да изолираш само тези от навигацията. Поиграй си, ще стане :).