Change Iframe Size Automatically To Fit Content & Prevent Scrollbars
Có thể bạn quan tâm
There are 2 ways to automatically change the size of an <iframe> so as to fit its content and prevent scrollbars :
- For same-domain iframes : From the parent page, the complete height & width of the iframe can be found through its contentDocument.body.scrollHeight & contentDocument.body.scrollWidth properties. These values can then be set as the CSS height & width of the <iframe> element.
- For cross-domain iframes : The iframe page can send a message to the parent page using postMessage(), informing about its size. On receiving the message, the parent page can change CSS height & width of the <iframe> element.
Same-Domain Iframes
For same-domain iframes, code changes are required only in the parent page. The iframe page needs no code changes.
- First we need to wait for the iframe to be loaded so that its correct dimensions are available.
- After iframe has been loaded, contentDocument.body.scrollHeight property gets its full height.
- contentDocument.body.scrollWidth property gets its full width.
Cross-Domain Iframes
For cross-domain iframes, code changes are needed in both the iframe & the parent page.
The iframe page needs to be loaded first to get correct dimensions. After loading, its dimensions are passed to the parent page using postMessage().
window.addEventListener('load', function() { let message = { height: document.body.scrollHeight, width: document.body.scrollWidth }; // window.top refers to parent window window.top.postMessage(message, "*"); });In the parent page, the message is recieved, and the <iframe> CSS dimensions are updated.
<iframe src="https://cross-domain.com/child.html" id="child-iframe"></iframe> <script> let iframe = document.querySelector("#child-iframe"); window.addEventListener('message', function(e) { // message that was passed from iframe page let message = e.data; iframe.style.height = message.height + 'px'; iframe.style.width = message.width + 'px'; } , false); </script>
Từ khóa » Html Iframe Size Auto
-
Make Iframe Automatically Adjust Height According To The Contents ...
-
Automatically Adjust IFrame Height According To Its Contents Using ...
-
How To Adjust The Width And Height Of Iframe To Fit With Content In It
-
Html Iframe Width Auto Code Example
-
Auto-resize Iframe When Content Size Changes - WillMaster
-
How To Automatically Resize An Iframe | By Bret Cameron
-
How To Create Responsive Iframes - W3Schools
-
HTML Iframe Height Attribute - W3Schools
-
3 Ways To Resize IFrames In HTML - WikiHow
-
Auto Resize IFrame (Same Origin) - Gists · GitHub
-
Auto Adjust HTML IFrame Height According To Page Contents JS
-
How To Resize Iframe Height Auto After Page Loaded Insideit - MSDN
-
How To Scale The Content Of
-
Iframe Height Auto Css