Javascript problem with iframe that's hidden b

2019-01-23 05:46发布

问题:

I have a page that contains an iframe that gets loaded using Javascript:

index.html

<iframe id="myFrame" width="800" height="600" style="display: none;"></iframe>
<div id="loader"><!-- some loading indicator --></div>

<script type="text/javascript">
function someFunction() {
  var myFrame = document.getElementById('myFrame');
  var loader = document.getElementById('loader');

  loader.style.display = 'block';

  myFrame.src = 'myFrame.html';
  myFrame.onload = function() {
    myFrame.style.display = 'block';
    loader.style.display = 'none';
  };
}
</script>

The page that gets loaded in the iframe contains some Javascript logic which calculates the sizes of certain elements for the purposes of adding a JS driven scrollbar (jScrollPane + jQuery Dimensions).

myFrame.html

<div id="scrollingElement" style="overflow: auto;">
  <div id="several"></div>
  <div id="child"></div>
  <div id="elements"></div>
</div>

<script type="text/javascript">
$(document).load(function() {
  $('#scrollingElement').jScrollPane();
});
</script>

This works in Chrome (and probably other Webkit browsers), but fails in Firefox and IE because at the time jScrollPane gets called, all the elements are still invisble and jQuery Dimensions is unable to determine any element's dimensions.

Is there a way to make sure my iframe is visible before $(document).ready(...) gets called? Other than using setTimeout to delay jScrollPane, which is something I definitely want to avoid.

回答1:

Some browsers assume that when "display:none" is applied to replaced elements (like Flash or an iframe) the visual info for that element is no longer needed. So, if the element is later displayed by the CSS, the browser will actually recreate the visual data form scratch.

I imagine that having the iframe default to "display:none;" makes the browser skip the rendering of the HTML so the tags don't have any dimensions. I would set the visibility to "hidden" or position it off the page rather than use "display:none;".

Good luck.



回答2:

instead of making the iframe invisible by using display:none, you could try to...

... set visibility:hidden

... set position:absolute; top:-600px;

... set opacity:0

or something else that makes jQuery "see" the objects but not the user (and reset the used css-attributes in your myFrame.onload function).



回答3:

visibility:collapse; display:hidden; height:0px;

Will work to get rid of white space too.. The iframe will also load..



回答4:

Hidden iframes are a huge security issue. Probably best to try to find another way to accomplish what you want, if it is legitimate, because hopefully future browsers will get rid of this feature altogether. http://blog.opendns.com/2012/07/10/opendns-security-team-blackhole-exploit/