var box = document.querySelector(".scroll-box")
var isDragging = false // 是否正在拖拽
var startX, startY, scrollLeft, scrollTop // 鼠标按下时的位置和盒子的滚动位置
//鼠标滚轮横向滚动
box.addEventListener("wheel", function (e) {
e.preventDefault()
let left = -e.wheelDelta || e.deltaY
box.scrollLeft = box.scrollLeft + left
})
//鼠标横向拖拽
box.addEventListener("mousedown", function (e) {
isDragging = true
startX = e.pageX - box.offsetLeft
startY = e.pageY - box.offsetTop
scrollLeft = box.scrollLeft
scrollTop = box.scrollTop
})
document.addEventListener("mousemove", function (e) {
if (isDragging) {
var distanceX = e.pageX - box.offsetLeft - startX
var distanceY = e.pageY - box.offsetTop - startY
box.scrollLeft = scrollLeft - distanceX
box.scrollTop = scrollTop - distanceY
}
})
document.addEventListener("mouseup", function () {
isDragging = false
})
鼠标横向拖拽/前端鼠标滚轮横向滚动/鼠标拖拽横向滚动
于 2024-06-18 16:52:10 首次发布