问题描述
使用下面的标记,当我单击或将鼠标悬停在#scrollUp或#scrollDown锚标记上时,如何向上或向下滚动#contentdiv。滚动应该是平滑的。如果点击它应滚动特定数量(对于触摸设备)如果鼠标悬停它可以滚动直到mouseout。
Using the markup below how would I get the "#content" div to scroll up or down when I click or hover over the "#scrollUp" or "#scrollDown" anchor tag. Scrolling should be smooth preferably. If clicked it should scroll a specific amount (for touch devices) if mouseover it can scroll until mouseout.
<style>
#content {
overflow:auto;
height: 50px; /*could be whatever*/
}
</style>
<a id="scrollUp" href="#">up</a>
<a id="scrollDown" href="#">down</a>
<div id="wrapper">
<div id="content">
<ul>
<li>some content here</li>
<li>some content here</li>
<li>some content here</li>
<li>some content here</li>
<li>some content here</li>
<li>some content here</li>
</ul>
</div>
</div>
推荐答案
你可以使用jQuery的功能,可在上实现平滑滚动效果点击
或鼠标悬停
:
You can use jQuery's animate
function to accomplish a smooth-scrolling effect on click
or mouseover
:
var step = 25;
var scrolling = false;
// Wire up events for the 'scrollUp' link:
$("#scrollUp").bind("click", function(event) {
event.preventDefault();
// Animates the scrollTop property by the specified
// step.
$("#content").animate({
scrollTop: "-=" + step + "px"
});
}).bind("mouseover", function(event) {
scrolling = true;
scrollContent("up");
}).bind("mouseout", function(event) {
// Cancel scrolling continuously:
scrolling = false;
});
$("#scrollDown").bind("click", function(event) {
event.preventDefault();
$("#content").animate({
scrollTop: "+=" + step + "px"
});
}).bind("mouseover", function(event) {
scrolling = true;
scrollContent("down");
}).bind("mouseout", function(event) {
scrolling = false;
});
function scrollContent(direction) {
var amount = (direction === "up" ? "-=1px" : "+=1px");
$("#content").animate({
scrollTop: amount
}, 1, function() {
if (scrolling) {
// If we want to keep scrolling, call the scrollContent function again:
scrollContent(direction);
}
});
}
工作示例:
(你将拥有禁用鼠标悬停
和 mouseout
事件以查看点击效果
事件处理程序正确)
(You'll have to disable the mouseover
and mouseout
events to see the effects of the click
event handler properly)
工作原理:
- 使用上面提到的
animate
函数在点击时按指定数量平滑滚动。 - 使用标志启用连续滚动当链接的
mouseover
事件处理程序被调用时,并在链接的mouseout
事件处理程序时禁用滚动。 - 当
调用scrollContent
时,如果滚动
标志仍为为true
动画完成后,再次以相同方向动画。animate
的回调函数参数允许我们在动画完成后执行操作。
- Uses the
animate
function mentioned above to scroll smoothly by a specified amount on click. - Uses a flag to enable continuous scrolling on when the link's
mouseover
event handler is called, and disable scrolling when the link'smouseout
event handler. - When
scrollContent
is called, if thescrolling
flag is stilltrue
after the animation is completed, animate again in the same direction. The callback function parameter ofanimate
allows us to take an action after animation has completed.
这篇关于如何使用jQuery在click和mouseover上创建可滚动的div滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!