我正在运行一个脚本(黑客)来欺骗 Safari 在响应式页面上正确调整视频大小。下面的脚本等待片刻然后隐藏,然后显示视频,使 Safari 意识到它应该将视频扩展到适当的大小。
我担心 $(document).ready
可能会过早触发脚本(即在视频加载之前),从而导致脚本无法执行其应执行的操作到视频。是否有可能使用 $(document).ready
脚本可能会触发,但由于视频在设置的毫秒后未加载,因此视频不会隐藏/显示?
我应该使用window.onload
(或其他方法?)来确保我的隐藏/显示大小调整技巧有效吗?
在我的测试中,该脚本大部分都可以工作,即使在我清除缓存时重新加载也是如此。但有几次,当我在随机计算机上加载页面时,视频的大小将无法正确调整,直到我重新加载页面。使用 window.onload 似乎不太理想,因为用户可能会在页面内容加载时注意到尺寸不正确的视频,或者在加载后看到黑客的行为。
<script><!-- Super hack to toggle display block/none which tricks Safari into properly sizing video-->
$(document).ready(function() {
$("#video1").delay(3000).hide(0, function() {
$("#video1").delay(3500).show();
});
});
</script>
最佳答案
这是两个事件之间的区别:
window.onload
在加载所有内容(即媒体和样式表)后触发。这是一个 DOM 事件$(document).ready()
在 HTML 文档加载后触发(即最后一个结束标记已加载,媒体和样式表可能尚未加载)。此事件在技术上是 jQuery 所独有的,但如果确实如此,jQuery 实际上会使用DOMContentLoaded
DOM 事件。
但是,jQuery 确实有一个仅在所有媒体加载后触发的事件,$(document).load()
,但是自 1.8 起已弃用
如果您希望代码在视频加载之前运行,请使用 $(document).ready()
如果您希望代码在视频加载后运行,请使用 window.onload
或 $(document).load()
回答您的评论:
Provided the video has loaded by the time the delay have finished (totals to
7.5 seconds
), your hack will work.Even if the video has not loaded, the HTML element still exists, so it can be hidden and shown even before the video has loaded (though I am not sure if the hack will still work, it depends on how and when Safari decides the size of the video).
Obviously if the video hasn't loaded, hiding and showing will not alter anything visually, since the element is empty / has no content.
关于javascript - $(document).ready 或 window.onload 用于隐藏/显示视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35227044/