本文介绍了根据可拖动元素滚动div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这基本上是我想要的:我想通过使用与jquery draggable绑定的另一个元素来上下滚动一个包含很长内容的div.

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

    }
});

这是有关更多信息的小提琴: http://jsfiddle.net/xNLsE/4/

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

推荐答案

这涉及几个步骤:

  1. 确定可拖动宽度与可滚动高度的比率.换句话说,您需要根据用户拖动的距离知道要滚动多少像素.

  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.

这最终看起来像这样:

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,我们将在以后使用.

I also included initialOffset which we'll use later.

将拖动的距离乘以比率,以定位可滚动元素.您将在可拖动元素的drag上执行此操作:

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.

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

这篇关于根据可拖动元素滚动div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:00