访问iframe DOM

时间:2015-03-11 02:19:18

标签: javascript iframe youtube onresize

我想停止YouTube回放onresize

我有一个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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

<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>