Need javascript to auto-scroll to the target html element after page loads

后端 未结 2 618
后悔当初
后悔当初 2021-01-03 02:34

I\'m backend developer, new to javascript. Can anyone provide a few lines of script that will allow the page to auto-scroll to the \"target\" element after the page loads

相关标签:
2条回答
  • 2021-01-03 02:38

    You can use scrollIntoView on the element in window.onload event..

    In your case you would be doing:

    window.onload = function() {
        var el = document.getElementById('target');
        el.scrollIntoView(true);
    }
    

    Good docs can be found here: MDN scrollIntoView

    0 讨论(0)
  • 2021-01-03 02:43

    Also change your body tag to something like

    <body onload="ScrollToTarget">
    

    Then your function can be defined in the header as

    function ScrollToTarget()
    {
         document.getElementById("target").scrollIntoView(true);
    }
    
    0 讨论(0)
提交回复
热议问题