為了方便引入了jquery:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{width:600px;margin: 0 auto;overflow-x: auto;background: #00a7d0;}
.child{width: 1000px;height: 500px;background: #0bb20c;}
</style>
</head>
<body>
<div class="box">
<div class="child">134567892</div>
</div>
</body>
<script src="jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(".child").on("mousedown",function(e){
let sx = e.offsetX;//記錄鼠標落入指示區域時的坐標
let lx = $(".box").scrollLeft();//記錄鼠標落入指示區域時滾動條已滾動的距離
let timer;//給個延遲器是為了防止高頻觸發一直抖
$("body").on("mousemove",function(e1){//給body加此事件是為了解決一些異常
if(e1.target.className=="child"){//判斷移動區域是否為child
let ex = e1.offsetX;//記錄移動時鼠標的橫坐標
let x = ex-sx;//移動時的坐標減去落入時的坐標
if(x<0){//如果小於0,說明鼠標是在往左邊拖動
timer = setTimeout(function(){
//這一步是因為鼠標往左拖動,實際坐標軸會往右移動,也就是滾動條滾動距離變大,取落入時的滾動距離加差值的絕對值
$(".box").scrollLeft(lx+Math.abs(x));
},0)
}
if(x>=0){//這一步就是上一判斷的反結果
timer = setTimeout(function(){
$(".box").scrollLeft(lx-x);
},0)
}}else{//這一步是判斷移動區域不為child,那么觸發body的mouseup事件
$("body").trigger("mouseup");
}
});
//mouseup事件,關閉當前mousemove事件,並將定時置空
$("body").on("mouseup",function(e){
$("body").off("mousemove");
timer = null;
})
})
</script>
</html>