基于JavaScript滚动的动画在移动设备上不稳定

时间:2016-10-14 07:16:04

标签: javascript animation mobile scroll smooth-scrolling

我有2个div(左和右),我想根据右边滚动左边。 https://jsfiddle.net/3jdsazhg/2/

这在桌面上工作正常,但是当我改用移动设备时,它不再流畅...... 通过更改

可以很容易地注意到这一点
_left.style.top = _content.scrollTop - (_content.scrollTop * ratioLeftRight) + 'px';

_left.style.top = _content.scrollTop + 'px';

它应该作为一个固定的定位div

  1. 我想知道为什么这不顺利的确切原因......我知道它不是动画。 div上的简单动画很流畅,当它基于滚动时会出现问题。
  2. 如何让这个动画流畅?

2 个答案:

答案 0 :(得分:3)

它可能不稳定,因为它在滚动时被点燃了,事实上我非常确定IOS mobile会在用户滚动时暂停javascript执行。

相反,我建议使用一个间隔,你可以调整每个间隔之间的时间到对你的用例感觉良好的时间。

虽然在使用滚动事件时它每隔X毫秒触发一次这个逻辑可能看起来很密集,但是你可能会每秒发射几百次事件,这将更加强烈和明显。用户使用具有限制处理能力的设备。

(function () {
     var interval = null,

         //Currently set at 0.4 seconds, play with the code
         //and change this value to see what works best for 
         //this use-case
         time_between_interval = 400;

     setInterval(scrollLogic, time_between_interval); 

     function scrollLogic () {
         //The function body of what you're assigning 
         //to the scroll event.
     } 

     //I have omitted clearing the interval but you would want to do that, perhaps on page change, or something.

     //clearInterval(interval);
})();

答案 1 :(得分:3)

I finally managed to think out a solution.

From my point of view, i'm guessing the mobile view fires the scroll event less often and because we are scrolling the wrapper, we first scroll the whole page and then scroll back with js the left part and because it's different from the desktop version, this issue becomes visible...

The solution was to change the left side to fixed position, and substract from the top instead of adding to it.

_left.style.top = -(_content.scrollTop * ratioLeftRight) + 'px';