访问 iframe DOM

Accessing iframe DOM

我想在调整大小时停止 YouTube 播放

我有一个 iframe

  <iframe id="tutube" class="youTubeVideo" frameborder="0" height="100%" width="100%" allowscriptaccess="always"
    src="https://youtube.com/embed/d3cRXJ6Ww44?showinfo=0&autohide=1&enablejsapi=1">
  </iframe>

和一个函数

function stopTheVideo(){
    var div = document.getElementById("tutube");
    var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
    div.style.display = state == 'hide' ? 'none' : '';
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
            };

我称之为

<body onresize="stopTheVideo();"

我得到

Uncaught TypeError: Cannot read property 'contentWindow' of undefinedindex10.html:198 toggleVideoindex10.html:206 resizeFunctionsindex10.html:31 onresize

有什么想法吗?

试试这个:

<body onresize="stopTheVideo();">
<div id="tutube">
    <iframe id="youTube" class="youTubeVideo" frameborder="0" height="100%" width="100%" allowscriptaccess="always"
    src="https://youtube.com/embed/d3cRXJ6Ww44?showinfo=0&autohide=1&enablejsapi=1">
      </iframe>
</div>
<script>
var state= 'hide';
function stopTheVideo(){
    var div = document.getElementById("tutube");
    var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
    div.style.display = (state == 'hide') ? 'none' : '';
    func = (state == 'hide') ? 'pauseVideo' : 'playVideo';
    iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
            };
</script>
</body>