How to get scrollTop of an iframe

后端 未结 10 1732
一生所求
一生所求 2020-12-03 03:33

jQuery\'s scrollTop returns null when window is an iframe. Has anyone been able to figure out how to get scrollTop of an iframe?

more info:

my script is runn

10条回答
  •  长情又很酷
    2020-12-03 03:49

    I have try to

    $('#myIframe').contents().scrollTop(0);
    

    and

     let scrollTop = document.getElementById(IFRAME_ID).contentWindow.document.body.scrollTop;
    

    the first function work success in desktop browser. not working in mobile browser. so I use another function with scrollIntoView

    $("#ButtonId").click(function() {
            var win = document.getElementById(IFRAMEID).contentWindow;
            var scrollTop = win.document.documentElement.scrollTop || win.pageYOffset || win.document.body.scrollTop;
            // scrollTop can getted
            if (scrollTop) {
                win.document.documentElement.scrollTop = 0;
                win.pageYOffset = 0; // safari
                win.document.body.scrollTop = 0;
            } else {
                win.document.body.scrollIntoView(true); // let scroll to the target view 
            }
        });
    

    scrollIntoView() view in scrollIntoView - MDN

提交回复
热议问题