在我完成我的第一个 jQuery 插件后,我开始开发这个。但是不知何故这个插件不起作用..我真的不明白出了什么问题,因为我确信我遵循了插件制作的所有规则。
编辑:“不起作用”是指网页上的元素没有任何反应。它甚至不返回错误。它只是行不通。
jQuery 插件基于普通的 javascript 源代码:您可以在这里看到一个工作示例和一个
jsfiddle
这些示例是用 javascript 制作的,而不是 jQuery 插件
这是我的插件
;(function($){
// We name the function loader
$.fn.loader = function (options) {
// Default settings - can be replaced by options
var defaults = {
speed: 5,
width: 50,
height: 50,
totalFrames: 19,
frameWidth: 50,
color: 'white',
loaderTimeout: false,
index: 0,
Xpos: 0,
frameDelay: 0
}
// Extend the options and defaults to variables
var opts = $.extend(defaults, options);
// We locate the loader Image
var loaderImage = '../../_resources/loading/loading_sprites_'+ opts.color + '_' + opts.height + '.png';
// Now start the Function
return this.each(function() {
// The original element is defined with a variable
var element = $(this);
var frameDelay = opts.frameDelay;
// We start out by defining the beginning of the animation
function startLoader() {
// The element is giving the right width and height to contain
// the loading animation, and the loaderImage source as background
element.width(opts.width).height(opts.height).css('background-image', 'url('+loaderImage+')');
// We calculate the Frames Per Second
FPS = Math.round(100/opts.speed);
frameDelay = 1 / FPS;
// And start the animation
setTimeout('continueAnimation()', frameDelay / 1000);
}
// To keep the animation on going we need to define a function
// that continuesly repeat the sprites
function continueAnimation() {
var Xpos = opts.Xpos;
var index = opts.index;
// The X-position is defined based on how wide the frame is
Xpos += opts.frameWidth;
// index is defined by continuelsy counting
index += 1;
// if index counts to more or equal to the amount of frames defined
if (index >= opts.totalFrames) {
Xpos = 0; // ... we set the X-position to be 0
index = 0; // ... and the index too
}
// We change the position og the sprite to give the illusion
// of an animation going on
element.css('background-position', Xpos + 'px 0');
// And finally we are going to ask our function to repeat itself.
setTimeout('continueAnimation()', frameDelay * 1000);
}
// Before anything we want the sprites to be pre-loaded
function imageLoader(source, start) {
var loaderTimeout = opts.loaderTimeout;
// First we clear Timout
clearTimeout(loaderTimeout);
loaderTimeout = 0;
// Then we generate a new image (the sprites)
genImage = new Image();
// When the image is loaded we want to start the animation
genImage.onload = function() {loaderTimeout = setTimeout(start, 0)};
// If we can't locate the sprite image, we prepare an error function
genImage.onerror = new Function('alert(\'Could not load the image\')');
// And we define the image source
genImage.src = source;
}
// This command starts the whole animation
new imageLoader(loaderImage, 'startAnimation()');
});
}
})(jQuery);
我这样称呼我的插件:
$(document).ready(function() {
$('.loader').loader({
color: 'blue'
})
});