开发者

How to remove the iframe body padding

ok i have bin struggling with this for quiet long nw...i am generating iframes dynamically using javascript...what im trying to do is to remove the default padding and margin and set it to 0px...heres my code

var newDiv = create_New_Div(); //this simple returns the id of the newly created
                           //div in javascript

        var iframeIdName="my"+inival_iframearea+"iframe";
        inival_iframearea++;
        var htcontents = "<iframe id='"+iframeIdName+"' frameborder='0'></iframe>";
        document.getElementById(newDiv).innerHTML = htcontents; 

if i do like <style> body {padding:0px;开发者_运维问答 margin:0px} </style> wat happens is that the main body has a zero padding and margin but when the iframe is generated after a user clicks a button, this style is not applied to the iframes body and has the default padding and margin which i donot want!! thanks!


Since you're not loading anything in the iframe, you have to grab the document therein and make the changes yourself.

var
   iframe = document.getElementById(newDiv).getElementsByTagName('iframe')[0];

function restyle() {
   var body = iframe.contentDocument.body;
   body.style.padding = 0;
   body.style.margin = 0;
}

iframe.onload = restyle;
restyle();

There are some caveats with respect to contentDocument, so you may see weird behavior in different browsers. Also, you may have trouble with accessing the document depending on how the browser interprets the lack of a src attribute. I've seen issues where the calling page is https, and the lack of src leads the browser to load about:blank, which has a different protocol and thus violates the Same Origin Policy.

The reason for the onload is that even though you're not loading a separate page, the browser still has to load ''something'' in there. YMMV.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜