Help me understand scrolling in javascript(jquery) terms
When you scroll, are you changing the position of something?
How can I change the position开发者_JS百科 of the scroll? Specifically to match the cursors movement.
What I want to do is scroll the window when I click and drag with the cursor inside the window.
For example: I have a 400px by 400px div with a 900px by 900px div inside of it. I want to scroll around by click and dragging. Note, I do NOT want to move the position of the inside div (easily doable with jQuery UI via draggable), just the scroll position. Moving the actual div position messes with my other javascript applications.
Any help would be appreciated! Thanks!
This should get you going with horizontal scrolling. Vertical would be similar, but with 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>
Edit: Return false after the mousedown is handled to prevent firefox from grabbing the div.
精彩评论