我正在开发一个小型 jQuery 插件,该插件根据容器 div 中的鼠标位置自动滚动容器 div 中的一组溢出元素。
这个想法是让这个插件成为我前一阵子写的东西的改进。请参阅此处左下角的自动滚动导航与此有关的老问题是,当您从除容器 div 的底部(javascript 透视图)之外的任何地方鼠标输入时,它会跳来跳去。
现在我的插件一切正常,但是当你从顶部鼠标输入时,它时不时地搞砸了(快速移动你的鼠标,它肯定会发生),我认为这是因为我从我的mouseenter 事件和我的 mousemove 事件都用于计算如何滚动内部元素。这是函数,源代码的其余部分非常小并且评论得体。
projList.mousemove(function(e){
//keep it from freaking out when we mouseenter from Top of div
if(enterMouseY > divHeight){
enterMouseY = divHeight;
}
mouseY = e.pageY-projList.offset().top;
//ok that didnt work... try to keep it from freaking out when we mouseenter from Top of div
if (mouseY > divHeight){
mouseY = divHeight;
}
//distnace from top of container div to where our mouse Entered
var distToTop = divHeight - enterMouseY;
//here is the calculation, I parameterize the mouseY pos as a value between 0-1
//0 being where we entered and 1 being the top or bottom of the div
//then multiply that by how much we have to scroll to get to the end of the list
//are we moving up or down
if(mouseY>enterMouseY){
//if up calculate based on Top
var dist =totalScrollDistance * ((mouseY-enterMouseY-projList.offset().top)/(distToTop));
}else if(mouseY<enterMouseY){
//if up calculate based on Bottom
var dist =totalScrollDistance * ((mouseY-enterMouseY-projList.offset().top)/(enterMouseY));
}else if(mouseY = enterMouseY){
var dist = 0;
}
//set the position of the list offsetting wherever we left it
pos = dist+lastPos;
//scroll to that position
projList.scrollTop(pos);
//are we trying to scroll past the scrollable amount
if(pos<0){
pos = 0;
}
if(pos>totalScrollDistance){
pos = totalScrollDistance;
}
$('#div1').text("mouseY: "+ mouseY +" enterMouseY: "+ enterMouseY +" distance:"+ dist.toFixed(1) + " pos:"+ pos.toFixed(1));
});