1、原始代码:
var move_x = function (dom) {
var init_x;
var box = document.querySelector(dom);
box.addEventListener("mousewheel", function (e) {
var v = -e.wheelDelta / 2;
box.scrollLeft += v;
e.preventDefault();
}, false);
box.onmousedown = function (e) {
init_x = e.pageX;
};
box.onmousemove = function (e) {
var move_x = init_x - e.pageX;
box.scrollLeft += move_x;
e.preventDefault();
};
};
2、deepseek改进后的代码:
var move_x = function (dom) {
var init_x;
var box = document.querySelector(dom);
var isDragging = false;
// 鼠标滚轮滚动(兼容现代浏览器)
box.addEventListener("wheel", function (e) {
box.scrollLeft += e.deltaY; // deltaY 表示垂直滚动量
e.preventDefault();
});
// 鼠标拖拽滚动
box.onmousedown = function (e) {
isDragging = true;
init_x = e.pageX;
e.preventDefault();
};
box.onmousemove = function (e) {
if (!isDragging) return;
box.scrollLeft += init_x - e.pageX;
init_x = e.pageX;
};
box.onmouseup = box.onmouseleave = function () {
isDragging = false;
};
};
3、全新优化代码:
var move_x = function (selector) {
const box = document.querySelector(selector);
let isDragging = false, startX, scrollLeft;
// 滚轮滚动(兼容现代浏览器)
box.addEventListener('wheel', (e) => {
box.scrollLeft += e.deltaY;
e.preventDefault();
});
// 拖拽逻辑
box.addEventListener('mousedown', (e) => {
isDragging = true;
startX = e.pageX - box.getBoundingClientRect().left;
scrollLeft = box.scrollLeft;
box.style.cursor = 'grabbing';
});
box.addEventListener('mouseleave', () => {
isDragging = false;
box.style.cursor = 'grab';
});
box.addEventListener('mouseup', () => {
isDragging = false;
box.style.cursor = 'grab';
});
box.addEventListener('mousemove', (e) => {
if (!isDragging) return;
e.preventDefault();
const x = e.pageX - box.getBoundingClientRect().left;
const walk = (x - startX) * 2;
box.scrollLeft = scrollLeft - walk;
});
};
早期的代码仍沿用旧时代码,新hondy.js已采用全新deepseek优化代码。
|