帮助我理解javascript(jquery)术语的滚动

时间:2010-10-26 19:19:11

标签: javascript jquery jquery-ui scroll

当你滚动时,你是在改变某些东西的位置吗?

如何更改滚动的位置?专门用于匹配游标运动。

当我在窗口内点击并拖动光标时,我想要做的是滚动窗口。

例如: 我有一个400px乘400px div,里面有900px乘900px div。我想通过点击和拖动来滚动。注意,我不想移动内部div的位置(通过draggable可以轻松地使用jQuery UI),只需要滚动位置。移动实际的div位置会混淆我的其他javascript应用程序。

任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:3)

这应该让你进行水平滚动。垂直将类似,但使用scrollTop()。

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript">
            var lastPageX;

            $(document).ready(function() {
                $("#inner").mousedown(function(e) {
                    // Reference to the drag pad
                    var inner = $(this);
                    // Position where mouse was pressed
                    lastPageX = e.pageX;
                    // Attach mouse move listener
                    $(inner).mousemove(function(e) {
                        var diff = lastPageX - e.pageX;
                        // Scroll based on the new curson position
                        $("#outer").scrollLeft($("#outer").scrollLeft() + diff);
                        lastPageX = e.pageX;
                    });
                    // Remove mouse move listener
                    $(window).mouseup(function() {
                        $(inner).unbind("mousemove");
                    });
                    return false;
                });
            });
        </script>
        <style>
            #outer {
                height: 400px;
                width: 400px;
                background-color: Lime;
                overflow: scroll;
            }
            #inner {
                height: 900px;
                width: 900px;
                background-color: Yellow;
            }
        </style>
    </head>
    <body>
        <div id="outer">
            <div id="inner">
            </div>
        </div>
    </body>
</html>

编辑:处理mousedown后返回false以防止firefox抓取div。