Can somebody please explain why this won't work? Ideally, when the link at the top is clicked, it should scroll down to my other class. I also don't understand a lot of this code, so a detailed explanation would be great!

$('a.scrollto').click(function(){
        $('html, body').animate({
            scrollTop: $( $.attr(this, 'href') ).offset().top-25
        }, 500);
        return false;
    });

有帮助吗?

解决方案

You have to make sure that each anchor with class "scrollto" has a HREF which points to an Class (or ID is more suggested). For example:

<a href="#goToThisAnchor" class="scrollto">Scroll to #goToThisAnchor</a>

Clicking the above anchor will scroll down to the element that has id="goToThisAnchor

//Put's the click event listeners on anchor elements with class name 'scrollto'
$('a.scrollto').click(function(){  
    $('html, body').animate({ //animates the html and body (this makes the scroll effect)
        scrollTop: $( $.attr(this, 'href') ).offset().top-25 //choose which element to scroll to in this case it will choose the element that is specified in the "href" of the anchor clicked. offset().top gives the position offset from the TOP of .your_class_name
    }, 500); //500 is the time in milliseconds it will take to scroll.
    return false; //cancels your anchor from following it's href
});

I would actually suggest using an ID instead of a class name to scroll to, or else the scrollTop will just scroll to the first element with the "class name" it sees.

You want to have this anchor to click on to scroll down to #rulesa:

<a href="#rulesa" class="scrollto">Scroll to #rulesa</a>

Clicking this anchor will scroll you to the element that has id="rulesa". Notice that the id is contained in the href.

My Apologies, using the following code will work:

$('a.scrollto').click(function(){
  $('html, body').animate({ 
     scrollTop: $("#rulespng").offset().top-25
  }, 500);
return false;

BUT You will have to recreate this function for EACH ID anchor you want to scroll to. Which is FINE, if you want all a.scrollto to scroll to just 1 anchor point: #rulespng

BUT If you use the original code it will be much more flexible:

scrollTop: $( $.attr(this, 'href') ).offset().top-25

You only need the one function listed at the top (which you also wrote in your original question), and it will work for ALL anchors with $('a.scrollto'), just depending on the href attribute of the anchor explained above.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top