You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在malihu mcustom scrollbar插件中实现点击按住内容左右滚动替代滚轮

实现malihu mcustom scrollbar点击按住拖拽左右滚动

1. 禁用默认鼠标滚轮滚动

初始化插件时关闭鼠标滚轮支持,确保只有拖拽操作触发滚动:

$(document).ready(function() {
  $(".scroll-container").mCustomScrollbar({
    axis: "x", // 启用横向滚动
    mouseWheel: { enable: false }, // 禁用鼠标滚轮滚动
    scrollInertia: 0 // 关闭滚动惯性,让拖拽更精准跟手
  });
});

2. 添加拖拽滚动逻辑

第一步:添加样式防止文字选中

给滚动容器添加样式,避免拖拽时选中文本影响体验:

.scroll-container {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

第二步:绑定鼠标事件实现拖拽

通过监听鼠标的按下、移动、松开事件,计算拖拽位移并调用插件滚动方法:

let isDragging = false;
let startX, initialScrollLeft;

$(".scroll-container").on("mousedown", function(e) {
  isDragging = true;
  // 记录初始鼠标位置和当前滚动偏移量
  startX = e.pageX - $(this).offset().left;
  initialScrollLeft = $(this).find(".mCSB_container").scrollLeft();
  // 可选:添加拖拽状态的视觉反馈样式
  $(this).addClass("dragging");
});

$(document).on("mousemove", function(e) {
  if (!isDragging) return;
  e.preventDefault();
  // 计算鼠标横向移动距离
  const currentX = e.pageX - $(".scroll-container").offset().left;
  const dragOffset = (currentX - startX) * 1; // 数值越大拖拽灵敏度越高,可自定义
  // 调用插件API滚动到目标位置
  $(".scroll-container").mCustomScrollbar("scrollTo", initialScrollLeft - dragOffset, {
    scrollInertia: 0
  });
});

$(document).on("mouseup", function() {
  isDragging = false;
  $(".scroll-container").removeClass("dragging");
});

关键注意事项

  • 必须确保插件初始化时axis设置为"x",开启横向滚动模式
  • dragOffset的乘数可根据需求调整,数值越大,鼠标移动相同距离时滚动的幅度越大
  • 绑定document的mousemove和mouseup事件,确保鼠标移出容器范围时仍能正常结束拖拽操作
  • 如果需要纵向拖拽滚动,只需将axis改为"y",并把scrollLeft替换为scrollTop

内容的提问来源于stack exchange,提问作者Rajasekar R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:22:37