Scroll by clicking and dragging inside div instead of clicking scrollbar
This CSS is for a DIV in an MVC2 application. The overflow:auto line adds a horizontal scrollbar to the div which is needed since the table in the div is very wide and extends past the edge of the page.
#main
{
padding: 30px 30px 15px 30px;
overflow:auto;/* this adds horizontal scroll*/
background-color: #fff;
margin-bottom: 30px;
_height: 1px; /* only IE6 applies CSS properties starting with an underscore */
}
Eventually there are going to be multiple tables stacked and the horizontal scroll bar is going to be below the bottom of the screen.
Is there a way to allow the users to click and 开发者_高级运维drag inside the div to make it scroll instead of actually having to click the scrollbar?
A very minimized JQuery approach to apply this functionality:
$.fn.attachDragger = function(){
var attachment = false, lastPosition, position, difference;
$( $(this).selector ).on("mousedown mouseup mousemove",function(e){
if( e.type == "mousedown" ) attachment = true, lastPosition = [e.clientX, e.clientY];
if( e.type == "mouseup" ) attachment = false;
if( e.type == "mousemove" && attachment == true ){
position = [e.clientX, e.clientY];
difference = [ (position[0]-lastPosition[0]), (position[1]-lastPosition[1]) ];
$(this).scrollLeft( $(this).scrollLeft() - difference[0] );
$(this).scrollTop( $(this).scrollTop() - difference[1] );
lastPosition = [e.clientX, e.clientY];
}
});
$(window).on("mouseup", function(){
attachment = false;
});
}
To apply it utilize:
$(document).ready(function(){
$("#divToScroll").attachDragger();
});
You need to implement three consecutive mouse event handlers in javascript for this:
- The mousedown handler should trigger a drag start by enabling the mousemove event handler (see 2)
- The mousemove handler should map the vertical mouse position to the scrollTop property of the div
- The mouseup handler should trigger a drag stop by disabling the mousemove event handler
Note that I don't think this is good user interface design: you're basically removing the ability to select text inside this div. Besides, the user can scroll using the mouse wheel, so I don't see the need for this.
精彩评论