横向鼠标拖动引发滚动条横向滚动

为了方便引入了jquery:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{600px;margin: 0 auto;overflow-x: auto;background: #00a7d0;}
.child{ 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>
原文地址:https://www.cnblogs.com/xinyouhunran/p/10969115.html