的下面的多個實例是一個簡單的視差插件的源代碼:創建jQuery插件
/*
Plugin: jQuery Parallax
Version 1.1.3
Author: Ian Lunn
Twitter: @IanLunn
Author URL: http://www.ianlunn.co.uk/
Plugin URL: http://www.ianlunn.co.uk/plugins/jquery-parallax/
Dual licensed under the MIT and GPL licenses:
http://www.opensource.org/licenses/mit-license.php
http://www.gnu.org/licenses/gpl.html
*/
(function($){
var $window = $(window);
var windowHeight = $window.height();
$window.resize(function() {
windowHeight = $window.height();
});
$.fn.parallax = function(xpos, speedFactor, outerHeight) {
var $this = $(this);
var getHeight;
var firstTop;
var paddingTop = 0;
//get the starting position of each element to have parallax applied to it
$this.each(function(){
firstTop = $this.offset().top;
});
if (outerHeight) {
getHeight = function(jqo) {
return jqo.outerHeight(true);
};
} else {
getHeight = function(jqo) {
return jqo.height();
};
}
// setup defaults if arguments aren't specified
if (arguments.length < 1 || xpos === null) xpos = "50%";
if (arguments.length < 2 || speedFactor === null) speedFactor = 0.1;
if (arguments.length < 3 || outerHeight === null) outerHeight = true;
// function to be called whenever the window is scrolled or resized
function update(){
var pos = $window.scrollTop();
$this.each(function(){
var $element = $(this);
var top = $element.offset().top;
var height = getHeight($element);
// Check if totally above or totally below viewport
if (top + height < pos || top > pos + windowHeight) {
return;
}
console.log(firstTop + " " + pos);
$this.css('backgroundPosition', xpos + " " + Math.round((firstTop - pos) * speedFactor) + "px");
});
}
$window.bind('scroll', update).resize(update);
update();
};
})(jQuery);
現在假設我調用插件,像這樣,在多個元素。
$('#intro').parallax("50%", .8);
$('#second').parallax("50%", 0.1);
$('.bg').parallax("50%", 0.4);
$('#third').parallax("50%", 0.3);
我真的在做什麼?創建插件的多個實例?
可以看到插件本身的演示HERE。
你的「插件」並不是一個插件。它似乎沒有保留任何實例信息(通常在元素的data()上)。你似乎有一個基本的jQuery擴展方法。你在更新單獨的元素時遇到問題嗎? –
@TrueBlueAussie,不,我沒有問題,只是好奇,關於以下內容http://chopapp.com/#exg6lhqe –
調用'.parallax()'調用'$ .fn.parallax'方法,你可以有完整的源代碼。你認爲它的哪一部分會「自動創建多個實例」?這甚至意味着什麼? – JJJ