admin管理员组

文章数量:1406937

Anyone know how I can scroll to a certain position on the page when clicking a link using JS? For instance, on click, scroll to a position 500px from the top of the window.

I am using the ScrollMagic plugin and my website content is being activated by scroll position so it is not possible for me to just use anchor links. Also it cannot be offset from the current position as this would not work either.

Any ideas?

Anyone know how I can scroll to a certain position on the page when clicking a link using JS? For instance, on click, scroll to a position 500px from the top of the window.

I am using the ScrollMagic plugin and my website content is being activated by scroll position so it is not possible for me to just use anchor links. Also it cannot be offset from the current position as this would not work either.

Any ideas?

Share Improve this question asked Jul 28, 2016 at 15:07 AFlyingLemonAFlyingLemon 191 silver badge3 bronze badges 1
  • 1 Simply use scrollTop(y) – Jose Rui Santos Commented Jul 28, 2016 at 15:13
Add a ment  | 

3 Answers 3

Reset to default 4

This should do the trick in pure js:

document.body.scrollTop = 500;

I recand doing it by jQuery :) Here is working on every device version

$(document).ready(function()  //When the page is ready, load function
{
    $("#some_id").click(function()  // When arrow is clicked
    {
        $("body,html").animate(
        {
            scrollTop : 500                       // Scroll 500px from top of body
        }, 400);  //how fast the scrolling animation will be in miliseconds
    });
});

Would something like this work? It'll give you a smooth scroll to that location for whatever link you attach it to.

$('a[href*=#]').click(function() {
    $('html, body').animate({scrollTop: 500}, 500);
}

本文标签: javascriptScroll to certain position from top of window on clickStack Overflow