Java脚本滚动功能调试

问题描述 投票:0回答:1

我一直在关注在线教程,所以这个答案可能非常简单,也许是我刚刚忽略的东西,但我似乎找不到我在JS中复制的滚动函数的任何错误。整个页面只有 HTML、CSS 和 JS,所以我想将滚动功能保留在 JS 中。

我想知道 JS 和 HTML 文件链接是否有问题?

我对此很陌生,因此非常感谢您的帮助!

这是我希望有滚动的 HTML;

   <section class="product">
        <h2 class="product-category">popular products</h2>
        <button class="pre-btn"><img src="img/arrow.png" width="60px" alt="Previous Item"></button>
        <button class="nxt-btn"><img src="img/arrow.png" width="60px" alt="Next Item"></button>
        
        <div class="product-container">
            <div class="product-card">
<!--White Pine and Sage Blend--> 
                <div class="product-image">
                    <!--Discount ON-->
                    <span class="discount-tag">25% off</span>
                    <img src="img/whitepinesage-blend.jpeg" class="product-thumb" alt="">
                    <button class="card-btn">add to wishlist</button>
                </div>
                <div class="product-info">
                    <h2 class="product-brand">White Pine and Sage</h2>
                    <p class="product-short-des">White pine, sage & lemon balm.</p>
                    <span class="price">$9</span><span class="actual-price">$12</span>
                </div>
            </div>

还有更多带有 class="product-card" 的 Div 可供滚动浏览,全部相同。

这是 Java 脚本;

const productContainers = [...document.querySelectorALL('.product-container')];
const nxtBtn = [...document.querySelectorALL('.nxt-btn')];
const preBtn = [...document.querySelectorALL('.pre-btn')];

productContainers.forEach((item, i) => {
    let containerDimensions = item.getBoundingClientRect();
    let containerWidth = containerDimensions.width;

    nxtBtn[i].addEventListener('click', () =>{
        item.scrollLeft += containerWidth
    })
    
    preBtn[i].addEventListener('click', () =>{
        item.scrollLeft -= containerWidth
    })
})

我正在关注的教程来自 YouTube 上的 Modern Web。

javascript html button scroll
1个回答
0
投票

querySelectorALL
替换为
querySelectorAll

© www.soinside.com 2019 - 2024. All rights reserved.