Simple pure Javascript drag controller slider

前端 未结 2 557
情深已故
情深已故 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

    <style>
    .range-slider {
      width:300px;
      height:20px;
      margin:0 auto 1em;
      position:relative;
      cursor:e-resize;
    }
    .range-slider:before {
      content:"";
      display:block;
      position:absolute;
      top:9px;
      left:0;
      width:100%;
      height:2px;
      background-color:black;
    }
    .range-slider span {
      display:block;
      height:inherit;
      position:relative;
      z-index:2;
      background-color:red;
      cursor:inherit;
    }
    </style>
    
    <div class="range-slider" id="range-slider-1">
      <span></span>
    </div>
    
    <script>
    rangeSlider('range-slider-1', function(value) {
        document.getElementById('test-area').innerHTML = value + '%';
    });
    </script>
    

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


    Update

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

    0 讨论(0)
  • 2021-02-01 10:30

    Take a look at DragDealer.js: https://skidding.github.io/dragdealer/

    There's an example of changing opacity of an image based on the value of a slider here.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题