2012-01-30 7 views
10

Questa dovrebbe essere una domanda piuttosto semplice, ma ho gettato la maggior parte della mia mattinata a questo punto, ea questo punto sono vicino a gettare la spugna. Non ho nemmeno un po 'di foo js - ma ho trovato un pezzo ben commentato di codice che spero di utilizzare per animare ancora la collega è:Contabilizzazione di un'intestazione fissa con animate.scrolltop e (target) .offset(). Top;

$(document).ready(function() { 
$('a[href*=#]').bind('click', function(e) { 
e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump 

var target = $(this).attr("href"); //Get the target 

var scrollToPosition = $(target).offset().top; 

// perform animated scrolling by getting top-position of target-element and set it  as scroll target 
$('html, body').stop().animate({ scrollTop: scrollToPosition}, 600, function() { 
    location.hash = target; //attach the hash (#jumptarget) to the pageurl 
}); 

return false; 

}); 
}); 

sto cercando di farlo 30px terreno sopra l'offset() in alto -. ho provato

$('html, body').stop().animate({ scrollTop: scrollToPosition -30}, 600,

cui quasi funziona - va al posto giusto, ma poi si riprende.

Ho anche provato

scrollTop: $(target).offset().top - 20 },

Ho anche provato

scrollTop: $(hash).offset().top + $('#access').outerHeight()

che non sembra cambiare nulla.

Sembra che la risposta potrebbe essere qui: JQuery page scroll issue with fixed header ma non riesco proprio a capirlo.

So che questo è simile ad altre domande - ma ho esaminato ciò che ho potuto trovare e sono abbastanza analfabeta da non essere stato in grado di copiare/incollare qualsiasi cosa risolva il problema.

Sarei incredibilmente grato per una soluzione.

Molte grazie,

Martin

PS

Questo altro pezzo di codice che ho trovato funziona ma è nudo l'hashtag, il che rende per lo più inutili.

$(function(){ 
$('a[href*=#]').click(function() { 
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    && location.hostname == this.hostname) { 
     var $target = $(this.hash); 
     $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); 
     if ($target.length) { 
      var targetOffset = $target.offset().top; 
      $('html,body').animate({scrollTop: targetOffset - 30}, 1000); 
      return false; 
     } 
    } 
    }); 
}); 

risposta

12

CURA: Hai solo bisogno di rilevare l'altezza della testata fissa e sottrarre che dal scrollToPosition che stavi facendo in modo corretto. Il problema è che lo window.location.hash = "" + target; salta la pagina in cima all'elemento con quell'ID. Quindi, se ti animi lì come stavi facendo e poi passasti a quel hash, "rimbalzerà" come hai descritto. Ecco il primo modo in cui possiamo combattere questo:

// Get the height of the header 
var headerHeight = $("div#header").height(); 

// Attach the click event 
$('a[href*=#]').bind("click", function(e) { 
    e.preventDefault(); 

    var target = $(this).attr("href"); //Get the target 
    var scrollToPosition = $(target).offset().top - headerHeight; 

    $('html').animate({ 'scrollTop': scrollToPosition }, 600, function(){ 
     window.location.hash = "" + target; 
     // This hash change will jump the page to the top of the div with the same id 
     // so we need to force the page to back to the end of the animation 
     $('html').animate({ 'scrollTop': scrollToPosition }, 0); 
    }); 

    $('body').append("called"); 
}); 

Ecco un nuovo jsfiddle per questo primo metodo: http://jsfiddle.net/yjcRv/1/

ULTERIORI EDIT: Un ancora modo migliore per controllare gli eventi di modifica di hash è quello di utilizzare un plug-in come jQuery Address. Con questo puoi usare molto di più i tuoi eventi di hashchange.Ecco un esempio di utilizzo:

// Get the height of the header 
var headerHeight = $("div#header").height(); 

$.address.change(function(evt){ 
    var target = "#" + evt["pathNames"][0]; //Get the target from the event data 

    // If there's been some content requested go to it…else go to the top 
    if(evt["pathNames"][0]){ 
     var scrollToPosition = $(target).offset().top - headerHeight; 
     $('html').animate({ 'scrollTop': scrollToPosition }, 600); 
    }else{ 
     $('html').animate({ 'scrollTop': '0' }, 600); 
    } 

    return false; 
}); 

// Attach the click event 
$('a').bind("click", function(e) { 
    // Change the location 
    $.address.value($(this).attr("href")); 

    return false; 
}); 

esempio vivo qui: http://www.vdotgood.com/stack/user3444.html

NOTA: Non è necessario aggiungere l'hash per il vostro link href ora. Ecco un link che si potrebbe bersaglio con un selettore jQuery:

<!-- This is correct --> 
<a href="/target" class="myclass">Target</a> 

<!-- These are incorrect --> 
<a href="/#/target" class="myclass">Target</a> 

<a href="#/target" class="myclass">Target</a> 

Per indirizzare questo link devi usare un selettore del tipo:

$("a.myclass").click(function(){ 
    $.address.value($(this).attr("href")); 
    return false; 
}); 

jQuery Indirizzo in effetti cercare i collegamenti che hanno i seguenti attributi:

<a href="/target" rel="address:/target">Target</a> 

il rel attribuire qui cont ains address: seguito da un url relativo definito dall'utente in questo caso /target. Se lo usi, l'indirizzo jQuery rileverà il collegamento e genererà automaticamente l'evento di modifica dell'hash.

+0

Grazie mille Steve. Giuro che imparerò a sufficienza per capire cosa sto facendo di copia e di sperimentazione, spero che quest'anno, ma questo mi abbia solo risparmiato il mal di testa. Cheers -m – Martin

+0

Domanda veloce: il codice funziona perfettamente, ma l'hash aggiunto all'URL sta diventando "#undefined" - qualche idea? – Martin

+0

Nessun problema amico. Continua a farlo, fai regolarmente dei buoni tutorial online e ti immergi nelle tue conoscenze! Scopri i siti Web tutsplus ([Webdesigntuts] (http://webdesign.tutsplus.com/), [Nettuts] (http://net.tutsplus.com/)) e [Team Treehouse] (http: // teamtreehouse .com /) web design/sviluppo apprendimento da Carsonified, tutte grandi risorse gratuite. –

5

So che questa è una vecchia domanda (sorta di), ma mi sono imbattuto in un problema simile con una navigazione a discesa fissa su un sito web. Si noti che questo è uno snippet di codice scorrevole, sebbene si possa facilmente renderlo automatico modificando la velocità dell'animazione.

jQuery:

$('body').on('click','a[href^="#"]',function(event){ 
    event.preventDefault(); 
    var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0; 
    //change this number to create the additional off set   
    var customoffset = 75 
    $('html, body').animate({scrollTop:target_offset - customoffset}, 500); 
}); 

Ho usato questo pezzo di codice per un lungo periodo di tempo senza problemi. L'unica cosa che non mi piace è che prenderà QUALSIASI tag #. Quindi, in un plugin come il plugin Flexslider in cui la navigazione usa #, li spoglio manualmente dal plugin.

1

Ho modificato la sceneggiatura originale da http://www.paulund.co.uk/smooth-scroll-to-internal-links-with-jquery. Funziona meraviglia ma non puoi impostare un ritardo così com'è.

var headerHeight = $("header").height(); 


     $(document).ready(function(){ 
    $('a[href^="#"]').on('click',function (e) { 
     e.preventDefault(); 

     var target = this.hash, 
     $target = $(target); 

     $('html, body').stop().animate({ 
      'scrollTop': $target.offset().top - headerHeight 
     }, 1200, 'swing', function() { 
      window.location.hash = target ; 
     }); 
    }); 
}); 

Sì, sono un po 'in ritardo, ma questo problema si è verificato solo a me ... Cheers!

Problemi correlati