如何检查用户向左或向右滚动?

时间:2013-06-26 05:47:59

标签: jquery

如何检查用户向左或向右滚动?

下面的代码是我尝试过的但不起作用....

$('.inner').scroll(function(){
    console.log('scroll');
    ol = $('.inner').scrollLeft();
    if(ol > $('.inner').scrollLeft()){
        //  console.log('right');
        //  ol = $('.inner').scrollLeft();
    }else{
        //  console.log('left');
        //  ol = $('.inner').scrollLeft();
    }
});

2 个答案:

答案 0 :(得分:5)

我已针对该问题尝试了另一种方法,您可以找到它正在运行here

我所做的是以下内容:

jQuery(document).ready(
    function($)
    {
        var lastLeftLocation = 0;

        $('.inner').scroll(
            function(e)
            {               
                if(lastLeftLocation > $(this).scrollLeft())
                {
                    console.log('It goes left');
                }
                else
                {
                    console.log('It goes right');
                }

                lastLeftLocation     =    e.currentTarget.scrollLeft;
            }
        );
    }
);

答案 1 :(得分:0)

我不确定您的HTML标记是什么样的,但您必须保存容器的scrollLeft并在滚动时对其进行比较。我还添加了一些逻辑来检测滚动开始和结束的时间。

var container = $('.outer');
var initVal = container.scrollLeft();
var isScrolling = false;
container.scroll(function(e){
    var curVal = container.scrollLeft();
    if (!isScrolling) {
        $(window).one("mouseup", function(e){
            console.log("Stopped scrolling at", container.scrollLeft());
            isScrolling = false;
        });
        console.log("Started scrolling at", curVal);
    }    
    if (curVal === initVal) return;
    if (curVal > initVal) {
        console.log("Scrolling right");
    } else {
        console.log("Scrolling left");
    }
    initVal = curVal;
    isScrolling = true;
});

请参阅test case on jsFiddle

相关问题