iframe on the page bottom: avoid automatic scroll of the page

后端 未结 7 1452
心在旅途
心在旅途 2020-12-25 13:46

I have an iframe from the middle to bottom on a page. When I load the page it scrolls to the bottom. I tried to body onload window.scroll(0,0) but

7条回答
  •  温柔的废话
    2020-12-25 13:47

    This is the solution I came up with and tested in Chrome.

    We have an iframe wrapped by a div element. To keep it short, I have removed the class names related to sizing the iframe. Here, the point is onMyFrameLoad function will be called when iframe is loaded completely.

    Then in your js file, you need this;

    function noscroll() {
      window.scrollTo(0, 0);
    }
    // add listener to disable scroll
    window.addEventListener('scroll', noscroll);
    function onMyFrameLoad() {
      setTimeout(function () {
        // Remove the scroll disabling listener (to enable scrolling again)
        window.removeEventListener('scroll', noscroll);
      }, 1000);
    }
    

    This way, all the scroll events become ineffective till iframe is loaded. After iframe is loaded, we wait 1 sec to make sure all the scroll events (from iframe) are nullified/consumed. This is not an ideal way to solve your problem if your iframe source is slow. Then you have to wait longer by increasing the waiting time in setTimeout function.

    I got the initial concept from https://davidwells.io/snippets/disable-scrolling-with-javascript/

提交回复
热议问题