可滚动 DIV 可以更新范围滑块吗?

Can a scrollable DIV update a Range Slider?

我有一个范围滑块,它在 DIV 中滚动内容。

如果单击可滚动区域,您将看到可以左右拖动可滚动区域 DIV。但是,当您这样做时,范围不会更新。手动滚动 DIV 时,有没有办法更新范围?我试图让 onscroll() 位置来更新范围,但没有成功。

https://jsfiddle.net/esoteric/fxtonew7/5/

//Range Slider
    var scroll = document.getElementById("scroll-range");
    var panel = document.getElementById("scrolling-container");

    var total = panel.scrollWidth - panel.offsetWidth;
    var percentage = total * (this.value / 100);
    var percentageWidth = total / 10; //10% for each +/- click

    scroll.oninput = function() {

        panel = document.getElementById("scrolling-container");
        total = panel.scrollWidth - panel.offsetWidth;
        percentage = total * (this.value / 100);
        panel.scrollLeft = percentage;
    }

    //Foward Arrow
    document.getElementById("increase").addEventListener("click",
        function() {
            scroll.stepUp(10);
            panel.scrollBy(percentageWidth, 0)
        });

    //Back Arrow
    document.getElementById("decrease").addEventListener("click",
        function() {
            scroll.stepUp(-10);
            panel.scrollBy(-percentageWidth, 0)
        });

        
    //Desktop grab and scroll
    const slider = document.getElementById("scrolling-container");
    let isDown = false;
    let startX;
    let scrollLeft;

    slider.addEventListener('mousedown', (e) => {
        isDown = true;
        slider.classList.add('active');
        startX = e.pageX - slider.offsetLeft;
        scrollLeft = slider.scrollLeft;
    });

    slider.addEventListener('mouseleave', () => {
        isDown = false;
        slider.classList.remove('active');
    });

    slider.addEventListener('mouseup', () => {
        isDown = false;
        slider.classList.remove('active');
    });

    slider.addEventListener('mousemove', (e) => {
        if (!isDown) return;
        e.preventDefault();
        const x = e.pageX - slider.offsetLeft;
        const walk = (x - startX) * 3;
        slider.scrollLeft = scrollLeft - walk;
    });

您需要做的是测试您滚动到的“面板”并更新滚动条位置

您可以通过添加另一个面板事件侦听器来做到这一点

    panel.addEventListener('mousemove', (e) => {
    // get scroll position in px
    console.log(panel.scrollLeft, panel.scrollTop);
    });

这将在控制台打印左边的位置

侦听您的 div 上的滚动事件,然后通过 div确定滚动位置和可能的最大滚动并设置值(如你的范围从 0 到 100) 到那个百分比

    slider.addEventListener('scroll', e => {
       const maxScrollLeft = slider.scrollWidth - scroll.clientWidth
       const percentage =  slider.scrollLeft / maxScrollLeft
       scroll.value = percentage * 100 // as percentage is normalized from 0 to 1
    })

您需要计算与拖动滑块时所做的相反的事情

panel.addEventListener('scroll', (e)=>{
    total = panel.scrollWidth - panel.offsetWidth;
    percentage = panel.scrollLeft / total
    scroll.value = percentage * 100
})

已更新 fiddle:https://jsfiddle.net/gaby/dwvtLn4g/8/