восемь восемь - 10 months ago 87
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 Source

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

$(function() {

$.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;
    border:1px solid red;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div class="container">
    <div class="slider" />
<div class="container">
  <div class="slider" />