Animate scroll to ID on page load

跟風遠走 提交于 2019-11-26 19:24:25
BumbleB2na

You are only scrolling the height of your element. offset() returns the coordinates of an element relative to the document, and top param will give you the element's distance in pixels along the y-axis:

$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);

And you can also add a delay to it:

$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);

Pure javascript solution with scrollIntoView() function:

document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
<h2 id="title1">Some title</h2>

P.S. 'smooth' parameter now works from Chrome 61 as julien_c mentioned in the comments.

AleX gRey
$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);

jquery-animate-body-for-all-browsers.

There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check this link.

In your case the code is

$("#title1").animatedScroll({easing: "easeOutExpo"});

try with following code. make elements with class name page-scroll and keep id name to href of corresponding links

$('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

for simple Scroll, use following style

height: 200px; overflow: scroll;

and use this style class which div or section you want to show scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!