Simple pure Javascript drag controller slider

前端 未结 2 556
情深已故
情深已故 2021-02-01 09:32

Hi Developers all over the world.

I would like to have some help with a simple, pure Javascript (30 lines), JQuery free (and other library\'s)

2条回答
  •  遇见更好的自我
    2021-02-01 10:19

    This code works in modern browsers. Just create some polyfill for that addEventListener and this custom range slider will be safe to use:

    function rangeSlider(id, onDrag) {
    
        var range = document.getElementById(id),
            dragger = range.children[0],
            draggerWidth = 10, // width of your dragger
            down = false,
            rangeWidth, rangeLeft;
    
        dragger.style.width = draggerWidth + 'px';
        dragger.style.left = -draggerWidth + 'px';
        dragger.style.marginLeft = (draggerWidth / 2) + 'px';
    
        range.addEventListener("mousedown", function(e) {
            rangeWidth = this.offsetWidth;
            rangeLeft = this.offsetLeft;
            down = true;
            updateDragger(e);
            return false;
        });
    
        document.addEventListener("mousemove", function(e) {
            updateDragger(e);
        });
    
        document.addEventListener("mouseup", function() {
            down = false;
        });
    
        function updateDragger(e) {
            if (down && e.pageX >= rangeLeft && e.pageX <= (rangeLeft + rangeWidth)) {
                dragger.style.left = e.pageX - rangeLeft - draggerWidth + 'px';
                if (typeof onDrag == "function") onDrag(Math.round(((e.pageX - rangeLeft) / rangeWidth) * 100));
            }
        }
    
    }
    

    Example Usage

    
    
    

    Demo: http://jsbin.com/dulifezi/2/edit


    Update

    I’m creating a repo for this snippet here → https://github.com/taufik-nurrohman/range-slider

提交回复
热议问题