更新时间:2023-12-01 22:49:58
截至 2019 年 10 月,这不再起作用(感谢 @CpnCrunch 的更新).它不会影响用户体验,您显然可以在页面加载后添加 1000 毫秒超时以使其生效.
as of October 2019, this is not working anymore (Thanks to @CpnCrunch for the update). For the cases where it's not impacting the user experience, you can apparently add a 1000ms timeout after the page load for it to take effect.
这是一个在页面加载时动态分配 src
的示例,使用纯 JS 解决方案.使用事件侦听器而不是 window.onload
因为对于后者,只能设置一个事件并且它会覆盖任何先例的 window.onload
事件:
This is an example of attibuting the src
dynamically on page load, using a pure JS solution. Using event listeners instead of window.onload
because with the latter, only one event can be set and it would override any precedent window.onload
event:
<iframe id="videoFrame" width="640" height="360" src="" frameborder="0" allowfullscreen></iframe>
<script>
function setVideoFrame(){
document.getElementById('videoFrame').src = 'http://example.com/';
}
if (window.addEventListener) // W3C DOM
window.addEventListener('load', setVideoFrame, false);
else if (window.attachEvent) { // IE DOM
window.attachEvent('onload', setVideoFrame);
}else{ //NO SUPPORT, lauching right now
setVideoFrame();
}
</script>
请注意,脚本可以在代码中的任何位置,但如果不支持事件侦听器(现在的浏览器不太可能),该函数会立即启动,因此至少应该在 iframe
元素.
Note that the script can be anywhere in the code, but in case of no support for event listeners (which is highly unlikely with nowadays browsers), the function is launched right away, so it should be at least after the iframe
element.