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

如何用变量替代固定值实现div的scrollLeft百分比滚动动画

按百分比实现div横向滚动动画

要把固定的500px滚动替换为百分比滚动,核心是先算出元素的可滚动总宽度,再乘以设定的百分比得到单次滚动距离,具体实现如下:

关键参数说明

  • scrollWidth:元素内容的总宽度(包含超出可视区域的部分)
  • clientWidth:元素的可视宽度
  • 可滚动总宽度 = scrollWidth - clientWidth

完整代码示例

// 定义滚动百分比,比如30%就设为0.3,可按需调整
const scrollPercentage = 0.3;

$('#button').click(function() {
  const $row = $('#row_01');
  // 计算单次滚动距离:可滚动总宽度 × 百分比
  const scrollDistance = ($row[0].scrollWidth - $row[0].clientWidth) * scrollPercentage;
  $row.animate({
    scrollLeft: `+=${scrollDistance}`
  }, 1000);
});

$('#button_alt').click(function() {
  const $row = $('#row_01');
  const scrollDistance = ($row[0].scrollWidth - $row[0].clientWidth) * scrollPercentage;
  $row.animate({
    scrollLeft: `-=${scrollDistance}`
  }, 1000);
});

可选优化

如果不想每次点击都重复计算滚动距离,可以把计算逻辑提前,页面加载时就算出固定值:

const $row = $('#row_01');
const totalScrollableWidth = $row[0].scrollWidth - $row[0].clientWidth;
const scrollPercentage = 0.3;
const scrollDistance = totalScrollableWidth * scrollPercentage;

$('#button').click(function() {
  $row.animate({ scrollLeft: `+=${scrollDistance}` }, 1000);
});

$('#button_alt').click(function() {
  $row.animate({ scrollLeft: `-=${scrollDistance}` }, 1000);
});

这样每次点击按钮,元素就会按照你设定的百分比距离滚动,而非固定的500px了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:44:56