问题
实现可拖动的进度条,类似于播放器那样。由于主要是应用在手机上,所以某些接口会因为浏览器内核的不同有所不同,没有做兼容性测试。Demo的平台为Android4.4,webview内核的话应该是chromium。
模型
在参考了网上一些代码后,决定实现模型如下(html):
html
<div class="progress-bar">
<div id="all-progress">
<div id="current-progress">
<span id="progress-button"></span>
</div>
</div>
</div>
用的嵌套布局。
css
/* 关于progress的整体框架 */
.progress-bar {
width : 100%;
}
/* 整条progress */
#all-progress {
width : 70%;
border-radius : 2px;
height : 4px;
background-color : #edca13;
overflow : visible;
}
/* 已播放progress */
#current-progress {
width : 50%;
border-radius : 2px;
height : 4px;
background-color : #124f5a;
}
/* 拖放 */
#progress-button {
width: 10px;
height: 10px;
display: block;
background-color: #0a6ebd;
border-radius: 5px;
position: relative;
top:-3px;
float: right;
}
js
var initProgress = function(){
music_bar = new scale("#progress-button","#all-progress","#current-progress");
};
scale = function(btn, bar, cur_bar){
this.btn = $$(btn);
this.bar = $$(bar);
this.cur_bar = $$(cur_bar);
this.minLength = this.bar.offset().left;
this.maxLength = this.minLength + this.bar.width();
this.currentX = this.btn.offset().left;
this.currentY = this.btn.offset().top;
this.init();
};
scale.prototype = {
init : function(){
var f = this;
document.addEventListener("touchstart", function(e1){
e1.preventDefault();
document.addEventListener("touchmove", function(e2){
var p = e2.touches[0];
var moveX = p.clientX;
var moveY = p.clientY;
if((Math.abs(moveX - f.currentX) < 20) && (Math.abs(moveY - f.currentY) < 20 )){
if(moveX < f.minLength){
f.cur_bar.css("width", "0%");
f.currentX = f.minLength;
}else if(moveX > f.maxLength){
f.cur_bar.css("width","100%");
f.currentX = f.maxLength;
}else{
var percent = ((moveX - f.minLength)*100)/(f.maxLength - f.minLength);
f.cur_bar.css("width",percent+"%");
f.currentX = moveX;
}
}
});
});
document.addEventListener("touchend", function(e){
document.addEventListener("touchmove",null);
});
}
};
initProgress();
touchstart 刚触摸webview控件时触发;
touchmove 触摸webview时会被不断触发;
touchend 触摸结束时触发。
这三个事件在手机的webview上产生,不会在pc浏览器上生效,分别对应着浏览器的onmousedown, onmousemove, onmouseup事件。
$$是我所用框架的Dom,可以等同于jquery的$。
效果