使用javascript在iframe上设置图像对象

时间:2013-03-10 05:21:54

标签: javascript html iframe

当我在该表中单击该图像时,我想在iframe中显示图像。问题是,在iframe中显示的图像太小(现在太大的图像不是问题)。所以当点击它并尝试执行必要的调整大小时,我试图在javascript函数中传递图像,但是在这里我将图像对象设置为iFrame的src时遇到了另一个问题。有什么建议?请指导我,如果你能提供帮助,我会节省很多时间。

这是我遇到问题的javascript代码。

function resize(e){
    var newImg = document.createElement('img');
    newImg.src = document.getElementById(e).src; 
    newImg.width = '448'; 
    newImg.height = '336';
    document.getElementById('passTo').src = newImg.src; /*newImg doesn't work aswell*/
}

这是我的HTML代码......

<tr>
  <td colspan="2" height="336">
    <iframe id = "passTo" name="A" src="Activity 6.html"  style="width:100%; height:100%;" scrolling="no" marginheight="0" marginwidth="0">
      <p>iframes are not supported by your browser.</p>
    </iframe>
  </td>
</tr>
<tr>
  <td><img src = "index.jpg" id = "myimg" border="3" height="48" width="64" onclick="resize(myimg)"></img></td>
  <td><img src = "index.jpg" id = "myimg2" border="3" height="48" width="64" onclick="resize(myimg2)"></img></td>
</tr>

1 个答案:

答案 0 :(得分:0)

我建议只设置iframe体的innerHTML:

function resize(e){
    var imgURL = document.getElementById(e).src;
    var iframe = document.getElementById('passTo');
    var html = "<img width='448' height='336' src=" + imgURL + ">";
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    doc.body.innerHTML = html;
}

或者,如果你想自己创建img对象并插入它,你可以这样做:

function resize(e){
    var imgURL = document.getElementById(e).src;
    var iframe = document.getElementById('passTo');
    // get iframe document in cross browser way
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    // create img object in the iframe's document.
    var img = doc.createElement("img");
    img.height = 336;
    img.width = 448;
    img.src = imgURL;
    doc.body.appendChild(img);
}

您之前尝试的内容有几个问题:

  1. 您将iframe.src设置为图片网址。执行此操作时,您无法控制height创建的width对象的imgiframe,它与其他img无关img你创建的对象。
  2. 您无法在一个文档中创建{{1}}对象,然后在另一个文档中使用它。
  3. 将一些HTML放在另一个文档中的最简单方法就是在其上设置HTML并让浏览器在正确的文档中创建对象。

    另外,请记住,如果iframe与运行代码的窗口/框架位于同一个域中,则只能修改或读取iframe的DOM内容(在您的示例中可以正常)。