【发布时间】:2011-12-30 23:59:43
【问题描述】:
我正在尝试为 youtube 播放器创建自己的“字幕”系统。目前我坚持使用无法正常工作的 js 滚动。
代码:
<script type="text/javascript" language="javascript">
var player;
var scrollToTimePosition;
// document.onReady
$(document).ready(function() {
var id = "QH2-TGUlwu4";
var params = { allowScriptAccess: "always" };
swfobject.embedSWF("http://www.youtube.com/v/" + id + "?enablejsapi=1", "video-container", "500", "375", "8", null, null, params, null);
});
// YouTube API Required function
function onYouTubePlayerReady() {
player = document.getElementById("video-container");
//player.playVideo();
setInterval(function() {
if(player.getPlayerState() == 1) {
var time = Math.round(player.getCurrentTime());
if(time > 1 && scrollToTimePosition != time) {
var anchor = $("#text-container > a[href=#"+time+"]");
if(anchor.length) {
scrollToTimePosition = time;
$('#text-container').animate({
scrollTop: anchor.offset().top - $("#text-container").offset().top
}, 1000);
}
}
}
}, 500);
}
</script>
你可以在网上看到它here(抱歉页面上的俄语)。在 Google Chrome 浏览器中,它有时会上下跳跃,并停在错误的位置。当滚动条已经滚动到某个位置并且下一个也部分可见时会发生这种情况。
UDP.:我添加了控制台日志以便于调试,日志如下所示:
Move to #33 with shift 204px
Move to #43 with shift 219px
Move to #46 with shift 261px
Move to #53 with shift 438px
Move to #60 with shift 480px
Move to #63 with shift 657px
Move to #65 with shift 915px
【问题讨论】:
-
有点与您的问题无关,但是当用户在视频中向前跳过时会发生什么?
-
该脚本在向前跳过时工作正常,因为间隔每 500 毫秒检查一次当前视频时间位置,我还想指出到目前为止不错的脚本。以前真的没有见过这样的东西。
-
@MeisamMulla,效果很好。当您向前跳过视频时,它会继续播放到下一个滚动点,然后字幕滚动到正确的位置。我想通过立即自动滚动到最近的位置来改善这一点。
标签: javascript jquery html scroll jquery-animate