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

jQuery实现可滚动菜单时div left滚动功能无效问题

解决滚动菜单无法左右移动的问题

嘿,我一眼就看出问题所在了——你给.scrollmenu加的left动画没效果,是因为这个元素默认是静态定位(position: static),这种定位下left属性根本不会生效!jQuery的animate()要修改left/top这类偏移属性,元素必须是相对、绝对或者固定定位才行。

下面给你具体的修复方案,以及一些优化建议:

核心修复步骤

只需要修改CSS里的.scrollmenu样式,加上相对定位就行,顺便给容器也加个相对定位,让滚动的参照更准确:

修改后的CSS代码

.container { 
  border: 0px solid red; 
  height: 45px; 
  overflow: hidden;
  position: relative; /* 让滚动菜单以容器为定位参照 */
}
.scrollmenu { 
  width: 300px; 
  background-color: #333; 
  overflow: auto; 
  white-space: nowrap;
  position: relative; /* 关键!添加相对定位,left属性才能生效 */
  left: 0; /* 初始化left值,让动画有明确的起点 */
}
.scrollmenu::-webkit-scrollbar { width: 0px; background: transparent; }
.scrollmenu a { display: inline-block; color: white; text-align: center; padding: 14px; text-decoration: none; }
.scrollmenu a:hover { background-color: #777; }
#right,#left{cursor:pointer;}

你的JS和HTML代码完全不用改,直接用原来的就行:

原JS代码(无需修改)

$("#left").on("click",function () { $(".scrollmenu").animate({left: '-=50'}, 'slow'); });
$("#right").on("click",function () { $(".scrollmenu").animate({left: '+=50'}, 'slow'); });

原HTML代码(无需修改)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<table border=1>
  <tr>
    <td id="left"><</td>
    <td>
      <div class="container">
        <div class="scrollmenu">
          <a href="#home">Home</a>
          <a href="#news">News</a>
          <a href="#contact">Contact</a>
          <a href="#about">About</a>
          <a href="#support">Support</a>
          <a href="#blog">Blog</a>
          <a href="#tools">Tools</a>
          <a href="#base">Base</a>
          <a href="#custom">Custom</a>
          <a href="#more">More</a>
          <a href="#logo">Logo</a>
          <a href="#friends">Friends</a>
          <a href="#partners">Partners</a>
          <a href="#people">People</a>
          <a href="#work">Work</a>
        </div>
      </div>
    </td>
    <td id="right">></td>
  </tr>
</table>

额外优化:添加边界检测

现在菜单虽然能滚动了,但可能会滚到空白区域,我给你加个边界判断,让菜单滚到最左/最右时就不再继续移动,体验更好:

$("#left").on("click",function () {
  const scrollMenu = $(".scrollmenu");
  // 计算菜单能滚动的最大左移距离(内容总宽度 - 容器可见宽度)
  const maxScrollLeft = scrollMenu[0].scrollWidth - scrollMenu.parent().width();
  const currentLeftOffset = Math.abs(parseInt(scrollMenu.css('left')));
  
  // 还没滚到最右边的话,继续左移
  if (currentLeftOffset < maxScrollLeft) {
    scrollMenu.animate({left: '-=50'}, 'slow');
  }
});

$("#right").on("click",function () {
  const scrollMenu = $(".scrollmenu");
  const currentLeftOffset = parseInt(scrollMenu.css('left'));
  
  // 还没回到最左边的话,继续右移
  if (currentLeftOffset < 0) {
    scrollMenu.animate({left: '+=50'}, 'slow');
  }
});

这样调整后,你的滚动菜单就能正常工作啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:56:13