之前工作需要一個回放的功能 不是視頻回放 是百度地圖API相關的移動軌跡回放
然後需要做些快進 倍速播放之類的 這篇就是抽出了我的進度條模塊
原作者已經找不到了 看到了@我加上轉載
我做了一些修改和補充
button其中changePercent爲例子方法 可以通過其中的公式來自動化控制進度條
其中*5是因爲scroll的寬度爲500px 這個地方要注意
例如scroll的寬度是150px 其中的計算就是*1.5 也可以 乘於寬度/100
<html>
<head>
<meta charset="UTF-8">
<title>歷史軌跡回放</title>
<style>
*{
margin: 0;
padding: 0;
}
.scroll{
margin:15px;
width: 500px;
height: 5px;
background: #ccc;
position: relative;
}
.bar{
width: 10px;
height: 20px;
background: #369;
position: absolute;
top: -7px;
left: 0;
cursor: pointer;
}
.mask{
position: absolute;
left: 0;
top: 0;
background: #369;
width: 0;
height: 10px;
}
</style>
</head>
<body>
<div class="scroll" id="scroll">
<div class="bar" id="bar">
</div>
<div class="mask" id="mask">
</div>
</div>
<input type="button" name="test" οnclick="changePercent(20)" value="跳轉到20%"></input>
<p>未開始</p>
<script>
var scroll = document.getElementById('scroll');
var bar = document.getElementById('bar');
var mask = document.getElementById('mask');
var ptxt = document.getElementsByTagName('p')[0];
var barleft = 0;
bar.onmousedown = function(event){
var event = event || window.event;
var leftVal = event.clientX - this.offsetLeft;
var that = this;
// 拖動一定寫到 down 裏面纔可以
document.onmousemove = function(event){
var event = event || window.event;
barleft = event.clientX - leftVal;
if(barleft < 0)
barleft = 0;
else if(barleft > scroll.offsetWidth - bar.offsetWidth)
barleft = scroll.offsetWidth - bar.offsetWidth;
mask.style.width = barleft +'px' ;
that.style.left = barleft + "px";
ptxt.innerHTML = "已經播放了" + parseInt(barleft/(scroll.offsetWidth-
bar.offsetWidth) * 100) + "%";
//防止選擇內容--當拖動鼠標過快時候,彈起鼠標,bar也會移動,修復bug
window.getSelection ? window.getSelection().removeAllRanges() :
document.selection.empty();
}
}
document.onmouseup = function(){
document.onmousemove = null; //彈起鼠標不做任何操作
}
function changePercent(percent) {
mask.style.width = percent*5+'px';
bar.style.left = percent*5+'px';
console.log(scroll.offsetWidth);
console.log(mask.offsetWidth);
ptxt.innerHTML = "已經播放了" + parseInt(mask.offsetWidth* 100/scroll.offsetWidth ) + "%";
}
</script>
</body>
</html>
順頌時祺