Home  >  Q&A  >  body text

javascript - How to center elements of iframe embedded page.

There is an element in a subpage in the iframe. I want it to be always centered as the mouse scrolls, but using the previous method, it seems to have no effect. May I ask why?

window.onload = function(){

            function box(){
                var oBox = document.getElementById("box");
                var L1 = oBox.offsetWidth;
                var H1 = oBox.offsetHeight;
                var Left = (document.documentElement.clientWidth-L1)/2;
                var top = (document.documentElement.clientHeight-H1)/2;
                oBox.style.left = Left+"px";
                oBox.style.top = top+"px";
            }
            box();
            window.onresize = function(){
            box()
        }
        }

The element whose id is box needs to be centered and position=absolute
Because the height of the element is not fixed, the js control used does not work for positioning; is there something wrong with my code or is it because the iframe page allows the element to be centered? Method not working

过去多啦不再A梦过去多啦不再A梦2601 days ago884

reply all(2)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-18 10:50:58

    你的iframe居中了吗? iframe的内容想居中的话,写css就可以了。不用写js了吧

    left:50%;top:50%;margin-left:-宽度的一半,高度同理

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-18 10:50:58

    好像得用 position=fixed

    reply
    0
  • Cancelreply