效果图:
注意点:
- 现象描述:鼠标按下进度条后滑出进度框才放开,则当鼠标回到进度条框内时,无需再次按下,也会自己触发进度条跟随鼠标的左右滑动
- 解决技巧:mouseup事件写成document.onmouseup;而不是big.onmouseup
<style>
#box{
width: 243px;
height: 30px;
margin: 100px auto;
}
#big{
width: 200px;
height: 20px;
background-color: #ccc;
float: left;
}
#small{
/* width: 10px; */
width: 0;
height: 20px;
background-color: pink;
}
span{
float: right;
}
</style>
<div id="box">
<div id="big">
<div id="small"></div>
</div>
<span>0</span>
</div>
var big = document.querySelector('#big')
var small = document.querySelector('#small')
var sp = document.querySelector('span')
big.onmousedown = function(){
big.onmousemove = function(e){
var e = e || window.event
var x = e.offsetX
small.style.width = x + 'px';
var pecen = Math.round(x/big.clientWidth*100)
pecen == 0 ? sp.innerHTML = pecen : sp.innerHTML = pecen + '%'
}
}
//要用documen.onmouseup,才可实现鼠标在框的外面松开后,不再触动进度条事件
//用big.onmouseup的话,鼠标按下进度条后,鼠标滑出框后松开,再回到进度条框上还会继续触发进度条事件
document.onmouseup = function(){
big.onmousemove = null
}