Scroll a div based on a draggable element

2019-08-12 07:39发布

问题:

Here's basically what I want: I want to scroll up and down a div which contains a very long content by using another element binded with jquery draggable.

<div id="wrapper">

<div id="container">

    <div id="timeline_wrapper">
        <div id="timeline">

        </div>
    </div>


    <div style="clear:both"></div>
    <div id="horizontal_control">
        <div id="controller"></div>
    <div>

</div>

$("#controller").draggable({
    revert: false,
    containment: "parent",
    axis: "x",
    create: function(){
        $(this).data("startLeft",parseInt($(this).css("left")));
        $(this).data("startTop",parseInt($(this).css("top")));
    },
    drag: function(event,ui){
        var rel_left = ui.position.left - parseInt($(this).data("startLeft"));
        var rel_top = ui.position.top - parseInt($(this).data("startTop"));

    }
});

here's a fiddle for more information : http://jsfiddle.net/xNLsE/4/

回答1:

This involves several steps:

  1. Determine the ratio of draggable width to scrollable height. In other words, you need to know how many pixels to scroll based on the distance the user has dragged.

    This ends up looking something like this:

    var $controller = $('#controller')
        // The total height we care about scrolling:
        , scrollableHeight = $('#timeline').height() - $('#timeline_wrapper').height()
        // The scrollable width: The distance we can scroll minus the width of the control:
        , draggableWidth = $('#horizontal_control').width() - $controller.width()
        // The ratio between height and width
        , ratio = scrollableHeight / draggableWidth
        , initialOffset = $controller.offset().left;
    

    I also included initialOffset which we'll use later.

  2. Multiply the distance dragged times the ratio to position the scrollable element. You'll do this on drag of the draggable element:

    $controller.draggable({
        revert: false,
        containment: "parent",
        axis: "x",
        drag: function (event, ui) {
            var distance = ui.offset.left - initialOffset;
    
            $('#timeline_wrapper').scrollTop(distance * ratio);
        }
    });
    

    Note that we have to take into account the initial offset of the scrollable control.

Example: http://jsfiddle.net/xNLsE/8/