2014-04-09 46 views
6

enter image description here我有一個iframe如何從iframe訪問文檔中的<img />?

<iframe src="../Images/landingpage.jpg" id="Iframe1" name="ifrmContent" class="ifrmClass"> 
</iframe> 

我在檢查元素髮現img標籤就在於它具有body標籤

<html> 
    <body style="margin: 0px;"> 
     <img style="-webkit-user-select: none;" src="../Images/landingpage.jpg"> 
    </body> 
</html> 

「#document」 我需要訪問這個IMG(「landingpage.jpg 「),以改變(圖像是小..需要調整)它的寬度爲100%,高度:90%

我已經嘗試使用#Iframe1>#document>html>body>img{width:100%;}

+2

控制檯中報告了6個錯誤。他們是什麼? – happyjack

回答

8

你可以這樣做:

$('#Iframe1').contents().find('img').css({'width':'100%','height':'90%'}); 

.contents()將爲您提供iframe的內容和.find()找到你的形象和.css()用於將樣式應用到找到圖像。

+0

無變化可見! – Joseph

+1

@Joseph這隻會在同一個域中工作,跨域策略將阻止您更改服務器之外的任何內容。 – ProllyGeek

+0

@pollyGeek我想我搞砸了js庫的某個地方!即時通訊仍然試圖找到它是否有任何其他錯誤..給出的答案看起來是正確的(但米不知道) – Joseph

7

嘗試

$("#Iframe1").contents().find("img").css({ 
    'width': '100%', 
    'height': '90%' 
}); 

.css()

.find()

.contents()

+0

我試過這個和debugged.But沒有變化是可見的! – Joseph

+1

@約瑟夫你應該看到控制檯的錯誤。圖片顯示你有6個錯誤。 –

1

確保您的$( 「#Iframe1」)選擇正在做的iframe完成後加載。

$(function() { 
    $("#Iframe1").contents().find('img').css({'width':'100%', 'height':'90%'}); 
}); 

或可讀性

$(document).ready(function() { 
    $("#Iframe1").contents().find('img').css({'width':'100%', 'height':'90%'}); 
}); 
1
$('#Iframe1').contents().find('img').css({'width':'100% !important','height':'90% !important'}); 

以防萬一高度由課堂作業覆蓋。

1

#document只是一個由您的瀏覽器生成的虛擬文檔,因爲您直接指向圖像 - 所以您無法通過此id標籤訪問它。

難道你只是調整iFrame?

$('#Iframe1').css({ 
    'width' : '100%', 
    'height' : '90%' 
}); 

,你可能需要一些CSS所以在iFrame的形象永遠是那樣大的iFrame:

iframe img { 
    height: 100%; 
    width: 100%; 
} 
2

您正在使用的iframe來加載圖像。存在文檔 - > html-> body-> img的原因是因爲您的瀏覽器正在將圖像請求格式化爲正確的HTML。

這可能是顯而易見的(而不是你以後),但這個特殊請求,你應該使用img標籤:

​​

然後,您可以輕鬆地更改寬度和高度,你會在您的網站中的任何其他元素。

4

非jQuery的選項

這個問題是非常相似的this one

基於上面的鏈接上回答問題,你可以嘗試:

var image = window.frames['Iframe1'].document.getElementByTagName('img')[0]; 
image.styles.width = '100%'; 
image.styles.height = '90%'; 
0

如果在iframe中加載的資源在您的域名 中,您可以使用jquery的

.contents().find('img').css() 

但如果從另一個域其加載你不能與客戶端腳本

0

訪問沒有必要訪問的iframe,只需使用CSS3。

將這些屬性添加到body或html(這是iframe)。

background: url("../Images/landingpage.jpg") no-repeat center center fixed; 
-webkit-background-size: cover; 
-moz-background-size: cover; 
-o-background-size: cover; 
background-size: cover; 

http://css-tricks.com/perfect-full-page-background-image/

無論如何,如果你preffer純JavaScript,你可以這樣做:

//Remember than the element should support percentage height. 
var tmp = window.frames['IframeID'].document.getElementById('ImgID').styles; 
tmp.width="100%"; 
tmp.height="90%"; 

此外,在jQuery的:

$('#Iframe1').contents().find('img').css({'width':'100%','height':'90%'}); 

https://stackoverflow.com/a/22953160/1107020

只是當然要讀這個:http://en.wikipedia.org/wiki/Same_origin_policy

希望比這個幫助在某種程度上。