Skip to content

Instantly share code, notes, and snippets.

@sakunyo
Last active December 11, 2015 11:18
Show Gist options
  • Save sakunyo/4592420 to your computer and use it in GitHub Desktop.
Save sakunyo/4592420 to your computer and use it in GitHub Desktop.
jquery.spriteOver.js

jquery.spriteOver.js

BackgroundPosition Sprite Animation と Margin Sprite Animation に対応した Sprite アニメーションロールオーバープラグイン

対応ブラウザ: E6+

/**
* Name : jquery.spriteOver.js
* Version : 1.0.1b
* Require : jQuery 1.8 +
*
* Author : Sakuya Sugo
* Date : 2013-01-22T14:49:34
* Licence : BSD Licence
*
* Function:
*/
(function($){
$.spriteOver = function( elem , options ){
// init
this.current = 0;
this.stepMax = options.stepMax || 0;
this.stepHeight = options.stepHeight || 0;
this.elem = $(elem);
this.speed = options.speed || 20;
// sptite type margin or BackgroundPosition
this.marginSprite = options.marginSprite || false;
// bg sprite option
this.pos = options.pos || 0;
this.initialize();
};
$.extend( $.spriteOver.prototype,{
animate : function (invert) {
if (this.timer) {
clearTimeout(this.timer);
}
if (invert) {
if (this.current < 1) {
return false;
}
this.movePosInvert();
} else {
if (this.current == this.stepMax) {
return false;
}
this.movePos();
}
return false;
},
movePosInvert: function () {
var self = this,
cssValue,
speed = this.speed;
cssValue = "-" + this.stepHeight * (this.current - 1) + "px";
if (this.marginSprite) {
this.timer = setTimeout(function () {
self.elem.css({ marginTop: cssValue });
self.current--;
self.animate(true);
}, speed);
} else {
this.timer = setTimeout(function () {
self.elem.css({ backgroundPosition: self.getBgPos(cssValue) });
self.current--;
self.animate(true);
}, speed);
}
},
movePos: function () {
var self = this,
cssValue,
speed = this.speed;
cssValue = "-" + this.stepHeight * this.current + "px";
if (this.marginSprite) {
this.timer = setTimeout(function () {
self.elem.css({ marginTop: cssValue });
self.current++;
self.animate(false);
}, speed);
} else {
this.timer = setTimeout(function () {
self.elem.css({ backgroundPosition: self.getBgPos(cssValue) });
self.current++;
self.animate(false);
}, speed);
}
},
getBgPos : function(value) {
return this.pos + "px " + value;
},
initialize: function () {
var self = this;
this.elem.on("mouseover focus", function(){
self.animate(false);
}).on("mouseout blur", function(){
self.animate(true);
});
}
});
$.fn.spriteOver = function( option ) {
return this.each(function() {
new $.spriteOver(this , option);
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment