问题描述:

I'm trying to add a div to a YouTube iframe element so that I can display things over the video. But this code:

<!DOCTYPE html>

<html>

<body>

<iframe id="player" width="854" height="480" src="https://www.youtube.com/embed/Jn9r0avp0fY" frameborder="0" allowfullscreen></iframe>

<script>

var player = document.getElementById('player');

var div = document.createElement('div');

div.id = 'newDiv';

div.innerHTML = 'Hello, world!';

player.appendChild(div);

</script>

</body>

</html>

has completely no effect. I can use JavaScript to confirm that the div is indeed in document.getElementById('player').children, but when inspecting elements on the page it is nowhere to be found. Why is this happening?

UPDATE: So I found this website https://www.reembed.com/ which succesfully overlays their own elements above the YouTube embedded iframe player, but I don't know how they achieve it.

网友答案:

This you can achieve using position absolute and top,left CSS properties for that div, no need to insert the div inside the Iframe.

网友答案:

Here is the solution to append element in the iframe.

<!DOCTYPE html>
<html>

<body>
    <iframe id="player" width="854" height="480" src="https://www.youtube.com/embed/Jn9r0avp0fY" frameborder="0" allowfullscreen></iframe>


    <script>
        setTimeout(function() {
            var player = document.getElementById('player');
            var iframeDocument = player.contentDocument || player.contentWindow.document;

            var div = document.createElement('div');
            div.id = 'newDiv';
            div.style.fontSize = '50px';
            div.innerHTML = 'Hello, world!';

            if (iframeDocument) {
                var iframeContent = iframeDocument.getElementsByTagName('body');
                console.log(iframeContent);
                iframeContent[0].appendChild(div);
            }

        }, 100);
    </script>
</body>

</html>
相关阅读:
Top