向下滚动而不是向左滚动

时间:2013-11-07 22:55:43

标签: javascript jquery orientation device

我正在尝试滚动页面的主体,当设备上下倾斜时,我正在向上和向下构建。

当设备倾斜时,此插件会左右滚动。

如何通过上下倾斜来上下滚动?

(function($) {
$.fn.tilt = function(params) {
    items = this;

    params = $.extend( {sensitivity: 1}, params);

    ax = ay = 0;

    window.addEventListener('devicemotion', function (e) {
        ax = e.accelerationIncludingGravity.x * params.sensitivity;
        ay = -e.accelerationIncludingGravity.y * params.sensitivity;

        if(ax > 0) {
            ax -= params.sensitivity;
            if(ax < 0) ax = 0;
        } else if(ax < 0) {
            ax += params.sensitivity;
            if(ax > 0) ax = 0;
        }

    }, false);

    mainLoop = setInterval("moveMe()");

    moveMe = function() {
        $(items).each(function() {
            scrollPos = $(this).scrollLeft() + ax;
            $(this).scrollLeft(scrollPos);
        });
    }
}
})(jQuery);

2 个答案:

答案 0 :(得分:1)

使用y参数做同样的事情吗?

(function($) {
$.fn.tilt = function(params) {
    items = this;

    params = $.extend( {sensitivity: 1}, params);

    ax = ay = 0;

    window.addEventListener('devicemotion', function (e) {
        ax = e.accelerationIncludingGravity.x * params.sensitivity;
        ay = -e.accelerationIncludingGravity.y * params.sensitivity;

        if(ay > 0) {
            ay -= params.sensitivity;
            if(ay < 0) ay = 0;
        } else if(ay < 0) {
            ay += params.sensitivity;
            if(ay > 0) ay = 0;
        }

    }, false);

    mainLoop = setInterval("moveMe()");

    moveMe = function() {
        $(items).each(function() {
            scrollPos = $(this).scrollTop() + ay;
            $(this).scrollTop(scrollPos);
        });
    }
}
})(jQuery);

答案 1 :(得分:0)

如果您使用的是jQuery,为什么不使用$.scrollTop()来修改元素的垂直滚动值?

var tilt_interval_id = setInterval(function(items) { onDeviceTilt(items); }, 50);    

function onDeviceTilt(items) {
   $(items).each(function() {
      var newScrollX = $(this).scrollLeft() + ax;
      var newScrollY = $(this).scrollTop() + ay;
      //Update the horizontal and vertical scroll positions
      $(this).scrollLeft(newScrollX);
      $(this).scrollTop(newScrollY);
   });
}

//Later, if you wish to clear the interval ...
clearInterval(tilt_interval_id);