Scroll a div based on a draggable element

自古美人都是妖i 提交于 2020-01-25 05:20:09

问题


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/



来源:https://stackoverflow.com/questions/18066277/scroll-a-div-based-on-a-draggable-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!