如何在JavaScript中以编程方式区分鼠标滚动和滚动? [英] How to distinguish scrolling by mouse from scrolling programmatically in JavaScript?

查看:120
本文介绍了如何在JavaScript中以编程方式区分鼠标滚动和滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过更改Javascript中的scrollLeft属性来滚动溢出的DIV内容:

I am scrolling an overflowing DIV's content by changing the scrollLeft property in Javascript:

setInterval(function(){
  $('#scrollbox').scrollLeft($('#scrollbox').scrollLeft()+1);
}, 50);

但是,我想在用户使用鼠标滚动内容后立即停止此操作。我尝试使用滚动事件检测到这一点

However, I want to stop this as soon as the user scrolls the content themselves, using the mouse. I tried to detect this using the scroll event

$('#scrollbox').scroll(function(){...});

但是,我上面的自动滚动也会触发该事件。我如何区分这个并且只对用户启动的滚动作出反应? (或者:如何阻止上面的代码触发滚动事件?这也可以解决问题)

however, my automatic scrolling above also triggers that event. How can I distinguish this and only react to user-initiated scrolling? (or: how can I stop the above code from firing a scroll event? That would also do the trick)

推荐答案

你可以使用 .hover():函数在鼠标悬停在滚动框元素上时停止滚动:

You could use the .hover(): function to stop the scrolling when the mouse is over the scrollbox element:

http://jsfiddle.net/bGHAH/1/

setInterval(function(){
    if(!mouseover)
    {
       $('#scrollbox').scrollLeft($('#scrollbox').scrollLeft()+1);
    }
}, 50);

var mouseover = false;
$('#scrollbox').hover(function(){
    mouseover = true;
},function(){
    mouseover = false;    
});






编辑

根据您的评论,我设法从以下网站找到了一个jquery插件: jquery的特殊滚动事件

Based on your comments I managed to find a jquery plugin from the following site: special scroll events for jquery.

此插件包含一个事件,该事件试图确定是否滚动根据最后一个滚动步骤和检查时间之间经过的时间段停止。

This plugin contains an event which attempts to determine whether scrolling has stopped based on the period of time that has elapsed between the last scroll step and the time the check was made.

要使这个工作起作用,我需要减慢你的间隔时间仅仅是插件使用的延迟时间为310毫秒。这样做意味着我必须增加滚动步骤以使其明显移动。

To get this to work I needed to slow your interval to just over the latency used by the plugin which worked out to be 310 milliseconds. Doing this meant I had to increase the scroll step to keep it visibly moving.

这是链接:

http://jsfiddle.net/EWACn/1/

,这是代码:

var stopAutoScroll = false;

$(document).ready(function(){

setInterval(function(){
    if(!stopAutoScroll)
    {
       $('#status').html('scrolling');
       $('#scrollbox').scrollLeft($('#scrollbox').scrollLeft()+10);
    }else{
       $('#status').html('not scrolling');
    }
}, 310);

$('#scrollbox').bind('scrollstart', function(e){
    stopAutoScroll = true;
});

$('#scrollbox').bind('scrollstop', function(e){
    stopAutoScroll = false;
});

});

希望这会有所帮助。

这篇关于如何在JavaScript中以编程方式区分鼠标滚动和滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆