2013-08-05 62 views
1

这里基本上是我想要的:我想通过使用绑定jQuery可拖动的另一个元素来上下滚动包含非常长的内容的div。滚动基于可拖动元素的div

<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")); 

    } 
}); 

这里得到更多信息,小提琴:http://jsfiddle.net/xNLsE/4/

+0

你想做什么?使用jQuery可拖动来创建滚动条? – putvande

+0

我想用draggable向上/向下滚动div。 – user1971075

+0

为什么不使用http://jscrollpane.kelvinluck.com/? Draggable并不是真正的意思。 – putvande

回答

0

这涉及几个步骤:

  1. 确定拖动宽度的比例可滚动的高度。换句话说,您需要知道基于用户拖动的距离来滚动多少个像素。

    这最终看起来是这样的:

    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; 
    

    我还包括initialOffset我们将在以后使用。

  2. 将拖动的距离乘以比率来确定可滚动元素的位置。你会做这样的拖动元素的drag

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

    请注意,我们必须考虑到初始的滚动控制的偏移。

例子:http://jsfiddle.net/xNLsE/8/

+0

这太神奇了。我会牢记这一点。非常感谢。 – user1971075