Igo*_*gor 3 javascript youtube-javascript-api progress-bar youtube-iframe-api
我一直在使用Youtube JavaScript API V3开发自定义播放器.这是我的代码的一部分:
在index.html我:
<div class="player_music-progressBar" id="player_music-progressBar"><div></div></div>
Run Code Online (Sandbox Code Playgroud)
styles.css:
.player_music-progressBar {
position: relative;
float: left;
width: 100%;
height: 6px;
background-color: #444444;
margin-top: 1px;
cursor: pointer;
}
.player_music-progressBar div {
height: 100%;
width: 0px;
background-color: #ccc;
}
Run Code Online (Sandbox Code Playgroud)
而且,在我JS这里是进行条形动画的功能:
function convert_time(seconds) {
var s = seconds,
h = Math.floor(s/3600);
s -= h*3600;
var m = Math.floor(s/60);
s -= m*60;
if(seconds >= "3600") {
return "0" + h + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
} else {
return (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
}
}
function progressBar(percent, element) {
var progressBar_width = percent * element.width() / 100;
element.find("div").animate({width: progressBar_width });
}
function onPlayerStateChange(event) {
if(event.data == YT.PlayerState.PLAYING) {
var playerTotalTime = player.getDuration();
playing = setInterval(function() {
var playerCurrentTime = player.getCurrentTime(),
playerDifferenceTime = (playerCurrentTime / playerTotalTime) * 100;
progressBar(playerDifferenceTime, $("#player_music-progressBar"));
}, 1000);
} else if(event.data == YT.PlayerState.PAUSED) {
clearInterval(playing);
}
}
Run Code Online (Sandbox Code Playgroud)
我想点击进度条时,点击进度条本地的秒数,所以,我尝试:
$("#player_music-progressBar").click(function(e) {
//player.seekTo(e.pageX - $("#player_music-progressBar").offset().left);
// to get part of width of progress bar clicked
var widthclicked = e.pageX - $(this).offset().left;
// do calculation of the seconds clicked
var calc = (widthclicked / player.getDuration()) * 100;
var calc_fix = calc.toFixed(0);
var time = convert_time(calc_fix);
console.log(time + " - " + widthclicked);
});
Run Code Online (Sandbox Code Playgroud)
但输出time是错误的(因为他是相对于进度条宽度,有固定宽度),我没有如何做这个计算的ideia ...怎么做?
总条宽为100%,单击的宽度为百分比.要获得相称的要求的时间做clickedWidth / totalWidth * player.getDuration():
$("#player_music-progressBar").click(function(e) {
var $this = $(this);
// to get part of width of progress bar clicked
var widthclicked = e.pageX - $this.offset().left;
var totalWidth = $this.width(); // can also be cached somewhere in the app if it doesn't change
// do calculation of the seconds clicked
var calc = (widthclicked / totalWidth * player.getDuration()); // get the percent of bar clicked and multiply in by the duration
var calc_fix = calc.toFixed(0);
var time = convert_time(calc_fix);
console.log(time + " - " + widthclicked);
});
Run Code Online (Sandbox Code Playgroud)