ScrollIntoView in Chrome

前端 未结 2 930
半阙折子戏
半阙折子戏 2021-01-17 21:36

I use:

var el = document.getElementById(\"centd\");
el.scrollIntoView(true);

to scroll to specific position. In every browser it works fine

相关标签:
2条回答
  • 2021-01-17 21:57

    I feel like it's supposed to be a feature and not a bug (but cannot find evidence to support this theory): it works fine the first time the page loads / in a new tab, but as soon as the user scrolled, that scroll-position overrides any scrollTo or scrollIntoView commands (in this briefly flashing fashion you described, and that I am currently trying to make sense of) – even if you wait for the document to be ready.

    Other browsers don't share this behavior, in my experience.

    0 讨论(0)
  • 2021-01-17 22:03

    Make sure all your JavaScript code is run after your page completes loading:

    document.addEventListener('DOMContentLoaded', function() {
       // your code here
    }, false);
    

    Or if you're using jQuery:

    $(document).ready(function(){
    // your code
    });
    

    This will make sure that your code runs the way you intend.

    0 讨论(0)
提交回复
热议问题