var flag = false; //mouse is clicked
var moveValue = 10; //scroll threshold value
var mouseY = 0; //Y coordinate
$(function(){
disableSelection(document.body);
$(\'body\').bind(\'mousedown\',function(event){
flag = true;
}).bind(\'mouseup\',function(event){
flag = false;
}).bind(\'mousemove\',function(event){
if(!flag) return;
if(mouseY < event.clientY){
window.scrollTo(0, GetPageScroll().Y + moveValue);
} else {
window.scrollTo(0, GetPageScroll().Y - moveValue);
}
mouseY = event.clientY;
});
});
function GetPageScroll() {
var x, y;
if(window.pageYOffset) {
// all except IE
y = window.pageYOffset;
x = window.pageXOffset;
} else if(document.documentElement
&& document.documentElement.scrollTop) {
// IE 6 Strict
y = document.documentElement.scrollTop;
x = document.documentElement.scrollLeft;
} else if(document.body) {
// all other IE
y = document.body.scrollTop;
x = document.body.scrollLeft;
}
return {X:x, Y:y};
}
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE
target.onselectstart=function(){return false;}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox
target.style.MozUserSelect="none";
else //All other ie: Opera
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
var moveValue = 10; //scroll threshold value
var mouseY = 0; //Y coordinate
$(function(){
disableSelection(document.body);
$(\'body\').bind(\'mousedown\',function(event){
flag = true;
}).bind(\'mouseup\',function(event){
flag = false;
}).bind(\'mousemove\',function(event){
if(!flag) return;
if(mouseY < event.clientY){
window.scrollTo(0, GetPageScroll().Y + moveValue);
} else {
window.scrollTo(0, GetPageScroll().Y - moveValue);
}
mouseY = event.clientY;
});
});
function GetPageScroll() {
var x, y;
if(window.pageYOffset) {
// all except IE
y = window.pageYOffset;
x = window.pageXOffset;
} else if(document.documentElement
&& document.documentElement.scrollTop) {
// IE 6 Strict
y = document.documentElement.scrollTop;
x = document.documentElement.scrollLeft;
} else if(document.body) {
// all other IE
y = document.body.scrollTop;
x = document.body.scrollLeft;
}
return {X:x, Y:y};
}
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE
target.onselectstart=function(){return false;}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox
target.style.MozUserSelect="none";
else //All other ie: Opera
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
用到2个帮助方法, 一个是得到滚动条的坐标, 还个是禁鼠标拖动选择, 最上的flag参数标示鼠标被按下才发生滚动, 这个参数可以根据需求去除.
本例用到了Jquery, 代码比较简单, 有兴趣可以修改成纯的js. so enjoy it