我试图在用户光标几乎到达视口末端时进行自动滚动
我编写了下面的代码,但它只运行一次,这意味着用户第一次靠近底部时自动滚动300px并停止。
只要用户位于视口的末尾,如何才能使其停止?
为什么它只能运作一次?
$(window).mousemove(function (e) {
var currposition = currentYPosition() + 800;
var MouseY = event.clientY;
if (MouseY > currposition-100) {
//Down
$('html, body').animate({
scrollTop: 300 // adjust number of px to scroll down
}, 1000);
}
});
答案 0 :(得分:0)
您可以使用此简单代码
$(".autoScrollBox").mousemove(function(e){
var clientY = e.clientY;
var boxHeight = $(this).height();
var contentHeight = $(".autoScrollBox")[0].scrollHeight;
var mousePositionProportion = clientY / boxHeight;
var scrollTop = mousePositionProportion * (contentHeight - boxHeight);
//// Top
if (clientY < boxHeight / 2)
scrollTop -= 50;
//// Bottom
else if (clientY > boxHeight - (boxHeight / 2))
scrollTop += 50;
$(".autoScrollBox").scrollTop(scrollTop);
});
&#13;
.autoScrollBox {
height: 150px;
overflow-y: hidden;
border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="autoScrollBox">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
<p>11</p>
<p>12</p>
<p>13</p>
<p>14</p>
<p>15</p>
<p>16</p>
<p>17</p>
<p>18</p>
<p>19</p>
<p>20</p>
</div>
&#13;
请参阅JSFiddle
中的更好示例