开发者

jQuery rotation function not firing.

I have the following jQuery extension:

(function ($) { //jQuery plugin extension

    jQuery.fn.rotate = function(degree, maxDegree) {
        this.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
        this.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});

          // Animate rotation with a recursive call
        rotation = setInterval(function() { 
            if (degree < (maxDegree/2)) { 
                $(this).rotate(++degree);
            } else {
                clearInterval(rotation);
            }
        },5);
    };
}(jQuery));

And I'm calling it like this:

$('#test').live('mouseover',function() {
                $(this).rotate(0, 360);
            });

But it doesn'开发者_C百科t fire, here is a JSFiddle: http://jsfiddle.net/neuroflux/8vZqr/

( Note, the fiddle won't run because of the live() )


You are not calling the function you have your plugin in:

(function ($) {
    $.fn.rotate = function(degree, maxDegree) {
        //...
    };
}(jQuery)); // <-- call

Furthermore, this inside the setInterval method does not refer to the selected elements anymore, but to window. You have to keep a reference to this:

var $self = this;
var rotation = setInterval(function() { 
    if (degree < (maxDegree/2)) { 
        $self.rotate(++degree);
     //...
};

I would als make rotation a local variable (with var) otherwise you will get in trouble if the function fires on several elements.

As for your fiddle, you did not select jQuery to use as library.

If this is all fixed, it works → .


You can also have a look to that jQuery plugin :

http://www.zachstronaut.com/projects/rotate3di/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜