当前位置: 动力学知识库 > 问答 > 编程问答 >

JavaScript / jQuery only works on second click

问题描述:

I'm developing a little site that loads a local HTML file into an iframe on click of a button. The iframe should be resized based on the size of the content of the local HTML file. The following almost works -- however, I need to click the "Fill" button twice in order to resize the iframe (Firefox).

I'm pretty sure it's got something to do with how events are being handled, but I've tried e.preventDefault() and return false without any luck. Any ideas?

<!DOCTYPE html>

<html lang="en-us">

<head>

<title>Load</title>

<meta charset="utf-8" />

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script>

$(function() {

$("#run").click(function(e) {

e.preventDefault();

var framex = document.getElementById('iframe');

framex.setAttribute("src", "local.html");

framex.style.height = (framex.contentWindow.document.body.scrollHeight + 50) + "px";

return false;

});

});

</script>

</head>

<body>

<input id="run" type="button" value="Load">

<div id="div" style="width: 100%; height: 600px; overflow: auto;">

<iframe id="iframe" width="100%" frameBorder="0">

</iframe>

</div>

</body>

</html>

网友答案:

The first time you are assigning framex.style.height, the page was not loaded yet, so the document has no size (or does not even exist, which would result in an error then).

You have to wait until the page was loaded:

framex.onload = function() {
    this.style.height = (this.contentWindow.document.body.scrollHeight + 50) + "px";
};
分享给朋友:
您可能感兴趣的文章:
随机阅读: