![](/img/trans.png)
[英]I want the page to scroll down, top automatically when my cursor is near the top or bottom of the page
[英]How use JQuery/Javascript to scroll down a page when the cursor at the top or bottom edge of the screen?
很简单, 我只想这样,当用户拖动一个项目并且它们到达视口的最底部或顶部(10px左右)时 ,页面(大约3000px长)轻轻向下或向上滚动,直到它们移动他们的光标(以及被拖动的项目)离开该区域 。
项是一个li标签,它使用jquery使列表项可拖动。 再具体一点:
我目前使用window.scrollBy(x = 0,y = 3)滚动页面并具有以下变量:
我怎样才能实现这一目标以及最适合这种情况的事件(目前在鼠标悬停中)? 我的想法:
我的最新尝试:
('li').mouseover(function(e) {
totalHeight = document.body.offsetHeight;
cursor.y = e.pageY;
var papaWindow = window;
var $pxFromTop = $(papaWindow).scrollTop();
var $userScreenHeight = $(papaWindow).height();
var iterate = 0;
do {
papaWindow.scrollBy(0, 2);
iterate++;
console.log(cursor.y, $pxFromTop, $userScreenHeight);
}
while (iterate < 20);
});
现在工作得非常好,用户只需要在拖动项目时“摇动”鼠标以保持滚动,但只需使用鼠标位置滚动它就相当坚固。 这是我最终使用的内容:
$("li").mouseover(function(e) {
e = e || window.event; var cursor = { y: 0 }; cursor.y = e.pageY; //Cursor YPos
var papaWindow = parent.window;
var $pxFromTop = $(papaWindow).scrollTop();
var $userScreenHeight = $(papaWindow).height();
if (cursor.y > (($userScreenHeight + $pxFromTop) / 1.25)) {
if ($pxFromTop < ($userScreenHeight * 3.2)) {
papaWindow.scrollBy(0, ($userScreenHeight / 30));
}
}
else if (cursor.y < (($userScreenHeight + $pxFromTop) * .75)) {
papaWindow.scrollBy(0, -($userScreenHeight / 30));
}
}); //End mouseover()
这不会起作用,因为当你的鼠标超过li时,事件才会触发。
('li').mouseover(function(e) { });
在拖动项目时,您需要能够告诉鼠标相对于视口的位置。 当用户开始拖动项目时,将“mousemove”事件附加到正文,然后检查鼠标位置并在必要时滚动。
$("body").on("mousemove", function(event) {
// Check mouse position - scroll if near bottom or top
});
别忘了在用户停止拖动时删除您的活动。
$("body").off("mousemove", function(event) {
// Check mouse position - scroll if near bottom or top
});
我从CodeProject获得每周简报(电子邮件),它有一些看起来肯定会解决我的问题...希望这可以帮助其他人:
http://johnpolacek.github.com/scrollorama/ - 基于JQuery并动画滚动
https://github.com/IanLunn/jQuery-Parallax - 基于JQuery,与上面类似
http:// remysharp。 com / 2009/01/26 / element-in-view-event-plugin / - JQuery,检测元素当前是否在用户视图中(对此问题非常有帮助!)
#2中的网站也有一些有趣的代码:
var windowHeight = $window.height(); var navHeight = $('#nav').height() / 2; var windowCenter = (windowHeight / 2); var newtop = windowCenter - navHeight; //ToDo: Find a way to use these vars and my original ones to determine scroll regions
这可能不是您想要的,但它可能会有所帮助。 当鼠标悬停在“屏幕边界”(用户定义的区域)上时,它将自动滚动。 假设屏幕右侧有一个40px宽的条,如果鼠标到达第一个1px,它将开始滚动。 你进入它的每个px,速度会增加。 它甚至还有一个很好的缓动动画。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.