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

Bootstrap箭头按钮绑定JavaScript滚动事件失效问题求助

问题解决:Bootstrap箭头按钮scrollLeft滚动失效处理

核心问题分析

  • document.getElementsByClassName() 返回的是HTMLCollection元素集合,并非单个DOM元素,直接调用scrollLeft无效果,必须取集合内的第一个目标元素(你的场景里只有一个.couponsimg容器)。
  • .couponsimg容器缺少必要CSS配置,未开启横向滚动条件:内容默认换行,不会产生横向溢出,导致scrollLeft属性无法触发滚动行为。

修正方案

1. 修复JavaScript代码

改用querySelector直接获取单个元素,避免集合操作的问题:

let rightArrow = document.getElementById('rightscroll')
let couponsimg = document.querySelector('.couponsimg')
let leftArrow = document.getElementById('leftscroll')

rightArrow.addEventListener('click',()=>{
    couponsimg.scrollLeft += 300
})

leftArrow.addEventListener('click',()=>{
    couponsimg.scrollLeft -= 300
})

2. 添加横向滚动CSS样式

给.couponsimg设置滚动相关样式,确保内容溢出时可横向滚动:

.couponsimg {
    overflow-x: auto; /* 开启横向滚动 */
    white-space: nowrap; /* 强制图片排成一行,不换行 */
    scrollbar-width: none; /* 隐藏Firefox滚动条 */
    -ms-overflow-style: none; /* 隐藏IE滚动条 */
}
/* 隐藏Chrome/Safari滚动条 */
.couponsimg::-webkit-scrollbar {
    display: none;
}
/* 给图片添加间距与固定宽度,优化显示效果 */
.couponsimg img {
    display: inline-block;
    margin-right: 15px;
    width: 200px;
    height: auto;
}

3. 可选:统一图片路径

注意到HTML中第二个图片的路径为img/coupon2.png,与其他图片的/img/xxx路径不一致,可能导致图片加载失败,建议统一路径:

<div class="couponsimg">
    <img src="/img/coupon1.png" alt="优惠券1">
    <img src="/img/coupon2.png" alt="优惠券2">
    <img src="/img/coupon3.png" alt="优惠券3">
    <img src="/img/coupon4.png" alt="优惠券4">
    <img src="/img/coupon5.png" alt="优惠券5">
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:52:18