簡體   English   中英

從Parent更改iFrame中的DIV的CSS

[英]Change the CSS of a DIV in an iFrame from Parent

我剛剛開始在我的工作中進一步發展我的網絡開發技能並且遇到了一個小問題。

我有一個iFrame(iframe.html),在這個iframe中,div是一個綠色方塊。 我想用我的父(index.html)中的按鈕和onClick函數更改iframe外部Div的顏色。

我嘗試了一些東西,比如調用普通函數(document.getElementById等)。 但沒有真正奏效。 所以我想,jquery可能有一些解決方案,我現在已經被困在這段代碼中,但它不起作用。

有人可以幫忙嗎?

PS:這不是一個跨學科的案例。 我在同一個目錄中得到了兩個html文件。

<!DOCTYPE html>

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <script src="jquery-1.12.2.min.js"></script>

        <title>buttonframetest</title>
        <script type="text/javascript">
            function Clickit() {
                 $(document).ready(function(){
            $('iframe').contents().find('background-color').css('backgroundColor', 'white');
            });
            }

        </script>

    </head>
    <body>
        <iframe id="iframe" src="iframe.html" width="500px;" height="500px">
        <p>iFrame nicht darstellbar in deinem Browser</p>
        </iframe>
        <br>
        <button type='button' onClick="Clickit();">Klick</button>
        <button type="button" onclick="redy">CHANGE</button>
        <br>
        <div class="ChangeColor"></div>


        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>

這可以使用DOM iframe對象的contentDocument屬性來完成:

document.frames[0].contentDocument.getElementById('id here').style['background-color']=whatever;

或者,使用window.postMessage

// this is in parent
document.frames[0].postMessage('red', '*');

// this is in frame
window.onmessage = function(x) {
    if (x.origin == 'http://www.example.com') document.getElementById('id here').style['background-color'] = x.data;
}

加上這個,

更新您的jQuery CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
function clck(){
       $(document).ready(function(){
        $('iframe').css({
        'background' : '#fff'
        });
        });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM