我想在调整大小时停止 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
有什么想法吗?
最佳答案
问题是您的代码期望您的 <iframe>
被包裹在另一个带有 id="tutube"
的元素中。 getElementsByTagName()
即使匹配,也不会选择调用它的元素。
因此,您可以重构 HTML,使其符合 JS 的期望:
<body onresize="stopTheVideo();">
<div id="tutube">
<iframe 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>
重写您的 JS,使其与您的 HTML 兼容:
function stopTheVideo(){
var iframe = document.getElementById("tutube").contentWindow;
div.style.display = state == 'hide' ? 'none' : '';
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
};
关于javascript - 访问 iframe DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977484/