восемь восемь - 1 month ago 19
Javascript Question

Moving a DIV by scrolling

I'm creating a jQuery scrollbar which scrolls the content in a <div>. It's something like jQuery ScrollPane.

I've come to the point where I need to move the scroll button. My question is: what is the best way to do it without any UI plugin? So when the user clicks on the scroll button it can be moved vertically in its parent container with a mousedown event. How could I do that?

Answer

Here's a starting point, hope that's what you're after:

$(function() {
    $('.slider').slider();
});

$.fn.slider = function() {
    return this.each(function() {
        var $el = $(this);
        $el.css('top', 0);
        var dragging = false;
        var startY = 0;
        var startT = 0;
        $el.mousedown(function(ev) {
            dragging = true;
            startY = ev.clientY;
            startT = $el.css('top');
        });
        $(window).mousemove(function(ev) {
            if (dragging) {
                // calculate new top
                var newTop = parseInt(startT) + (ev.clientY - startY);
                
                //stay in parent
                var maxTop =  $el.parent().height()-$el.height();          
                newTop = newTop<0?0:newTop>maxTop?maxTop:newTop;
                $el.css('top', newTop );
            }
        }).mouseup(function() {
            dragging = false;
        });
    });
}
.container{
    position:relative;
    border:1px solid red;
    height:100px;
}
.slider{
    height:20px;
    width:20px;
    background:green; 
    position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="container">
    <div class="slider" />
  </div>
</div>
<br/>
<div class="container">
  <div class="slider" />
</div>