0

我创建了这段代码来提高我的网页性能。如果autoplay.v.mystart为true,则不会播放2个幻灯片的滑动和动画,我对此做了条件。我的目标是在用户滚动时停止动画并在用户停止滚动时重新激活它,我认为这将减少网页负载,使网页滚动更流畅,因为我听人们说停止未使用的动画或隐藏未使用的东西。但是,我发现它并没有变得更顺畅,而是更加滞后。是否使用滚动事件侦听器和计时器/清除超时也会占用大量资源?实现我的目标、减少网页负载的最佳方法是什么?我在想我应该删除这段代码吗?那将是一种浪费,我无法决定

var saviour = {
    '$mywrapper' : $('#wrapper'),
    'mychecked':false,
    run : function(){
        var wrapper_timer;
        saviour.$mywrapper.scroll(function(){
            if(saviour.mychecked==false){
                saviour.mychecked = true;
                autoplay.v.mystart = false;
                clearTimeout(wrapper_timer);
                setTimeout(function(){saviour.mychecked=false},1000);
                wrapper_timer = setTimeout(function(){
                autoplay.v.mystart = true;
                console.log('autoplay restart')
                },4000);
                console.log('check');
            }
        });
    }
}
saviour.run();
4

1 回答 1

1

首先,这是一个 jQuery 插件,它基于this提供 'scrollstart' 和 'scrollstop' 事件,它是为早期版本的 jQuery 编写的,需要进行现代化改造。

(function($, latency) {
    var special = $.event.special;
    special.scrollstart = {
        setup: function() {
            var timer;
            function handler(evt) {
                if (timer) {
                    clearTimeout(timer);
                } else {
                    evt.type = 'scrollstart';
                    $.event.handle.apply(this, arguments);
                }
                timer = setTimeout(function() {
                    timer = null;
                }, latency);
            };
            $(this).on('scroll.start', handler);
        },
        teardown: function() {
            $(this).off('scroll.start');
        }
    };
    special.scrollstop = {
        setup: function() {
            var timer;
            function handler(evt) {
                var _self = this,
                    _args = arguments;
                if (timer) {
                    clearTimeout(timer);
                }
                timer = setTimeout(function() {
                    timer = null;
                    evt.type = 'scrollstop';
                    $.event.handle.apply(_self, _args);
                }, latency);
            };
            $(this).on('scroll.stop', handler);
        },
        teardown: function() {
            $(this).off('scroll.stop');
        }
    };
})(jQuery, 300);

这个版本:

  • 用and替换.bind()and ,加上相关的简化。.unbind().on().off()
  • 允许将延迟指定为自执行函数包装器的参数。

有了“scrollstart”和“scrollstop”事件检测,用于启动和停止动画的应用程序片段可以像这样简单:

$(window).on ('scrollstart', function(e) {
    allowAnim = false;    
    stopAnim();
}).on ('scrollstop', function(e) {
    allowAnim = true;
    anim();
}).trigger('scrollstop');

where anim()and stopAnim()are your functions for start and stop animation(s) and allowAnimis an boolean var in an external scope。

您可能需要调整延迟。我发现 300 大约是可接受的最小值,而且反应灵敏。较大 较高的值会降低响应速度,但会更好地防止动画在滚动中途重新启动。

演示

于 2012-11-28T15:28:41.010 回答