Minulý týden jsem uvolnil úryvek kódu pro MooTools, který vám umožnil zobrazit a vypnout odkaz „nahoru“ na jakékoli stránce. Zde je návod, jak implementovat tuto funkci pomocí jQuery.
Zobrazit ukázkuXHTML
<a href="#top" id="top-link">Top of Page</a>
Jednoduchý odkaz.
CSS
#top-link { display:none; position:fixed; right:5px; bottom:5px; color:green; font-weight:bold; text-decoration:none; border:1px solid green; background:Lightgreen; padding:10px; }
Trochu CSS pro pozici a styl.
JavaScript jQuery
//plugin jQuery.fn.topLink = function(settings) { settings = jQuery.extend({ min: 1, fadeSpeed: 200 }, settings); return this.each(function() { //listen for scroll var el = $(this); el.hide(); //in case the user forgot $(window).scroll(function() { if($(window).scrollTop() >= settings.min) { el.fadeIn(settings.fadeSpeed); } else { el.fadeOut(settings.fadeSpeed); } }); }); }; //usage w/ smoothscroll $(document).ready(function() { //set the link $('#top-link').topLink({ min: 400, fadeSpeed: 500 }); //smoothscroll $('#top-link').click(function(e) { e.preventDefault(); $.scrollTo(0,300); }); });
Uvidíte, že jsem přidal zásuvný modul ScrollTo jQuery, abych kotvě dodal trochu plynulosti.
Vezměte prosím na vědomí, že tato verze nefunguje s Internet Explorerem, protože IE nemá podporu CSS "position:fixed". Zde je pokus o podporu IE:
//plugin jQuery.fn.topLink = function(settings) { settings = jQuery.extend({ min: 1, fadeSpeed: 200, ieOffset: 50 }, settings); return this.each(function() { //listen for scroll var el = $(this); el.css('display','none'); //in case the user forgot $(window).scroll(function() { //stupid IE hack if(!jQuery.support.hrefNormalized) { el.css({ 'position': 'absolute', 'top': $(window).scrollTop() + $(window).height() - settings.ieOffset }); } if($(window).scrollTop() >= settings.min) { el.fadeIn(settings.fadeSpeed); } else { el.fadeOut(settings.fadeSpeed); } }); }); };Zobrazit ukázku
Znáte lepší způsob, jak začlenit podporu IE? Sdílejte!