垂直滚动视差背景效果 [英] Vertical scrolling parallax background effect
问题描述
我被要求编写一个脚本,为项目创建垂直滚动视差背景效果。我最初的尝试看起来像这样:
I have been asked to write a script that will create a vertical scrolling parallax background effect for a project. My initial attempt looks a little something like this:
(function($){
$.fn.parallax = function(options){
var $$ = $(this);
offset = $$.offset();
var defaults = {
"start": 0,
"stop": offset.top + $$.height(),
"coeff": 0.95
};
var opts = $.extend(defaults, options);
return this.each(function(){
$(window).bind('scroll', function() {
windowTop = $(window).scrollTop();
if((windowTop >= opts.start) && (windowTop <= opts.stop)) {
newCoord = windowTop * opts.coeff;
$$.css({
"background-position": "0 "+ newCoord + "px"
});
}
});
});
};
})(jQuery);
// call the plugin
$('.lines1').parallax({ "coeff":0.65 });
$('.lines1 .lines2').parallax({ "coeff":1.15 });
此代码确实提供了所需的效果,但滚动事件上的绑定是一个真正的性能消耗。
This code does give the required effect, but the bind on the scroll event is a real performance drain.
第1部分。如何更改插件以提高效率?
第2部分。是否有任何资源(书籍,链接,教程)我可以阅读以了解更多信息?
Part 1. How could I change my plugin to be more efficient? Part 2. Are there any resources (books, links, tutorials) I can read to find out more?
推荐答案
你可以尝试这样的事情:
You may try something like:
(function($){
$.fn.parallax = function(options){
var $$ = $(this);
offset = $$.offset();
var defaults = {
"start": 0,
"stop": offset.top + $$.height(),
"coeff": 0.95
};
var timer = 0;
var opts = $.extend(defaults, options);
var func = function(){
timer = 0;
var windowTop = $(window).scrollTop();
if((windowTop >= opts.start) && (windowTop <= opts.stop)) {
newCoord = windowTop * opts.coeff;
$$.css({
"background-position": "0 "+ newCoord + "px"
});
}
};
return this.each(function(){
$(window).bind('scroll', function() {
window.clearTimeout(timer);
timer = window.setTimeout(func, 1);
});
});
};
})(jQuery);
因此,如果有多个滚动事件是序列,浏览器将不会滚动背景。我在事件处理程序之外写了 func
,以避免在每个事件中创建一个新的闭包。
So the browser will not scroll the background if there are multiple scroll events is sequence. I wrote func
outside the event handler to avoid the creation of a new closure in every event.
这篇关于垂直滚动视差背景效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!