2013-01-02 40 views
1

我试图建立,将滑下去了特定的div我会在后面的脚本中提到的功能所有的时间滑动,下面的代码:创建功能DIV向下和向上

<!DOCTYPE html> 
<html> 
<head> 
    <style> 
    div { background:yellow; border:1px solid #AAA; width:80px; height:80px; margin:0 5px; float:left; } 
    div.colored { background:green; } 
    </style> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 
    <button id="run">Run</button> 

    <div></div> 
    <div id="mover"></div> 
    <div></div> 
<script> 

    $("button#run").click(function(){ 
    $("div:animated").toggleClass("colored"); 
    }); 

    function animateIt() { 
    return $(this).slideToggle(5000, animateIt); 
    } 

    $("div#mover").animateIt(); 

</script> 

</body> 
</html> 

但它给我这个错误“遗漏的类型错误:对象的翻译:有没有方法‘animateIt’”

Here's a fiddle

在此先感谢。什叶派...

回答

3

animateIt不是jQuery方法。把它作为一个经常性的功能,并传入元素:

function animateIt ($element) { 
    $element.slideToggle(5000, function(){ 
     animateIt($element); 
    }); 
} 

animateIt($("div#mover"));​ 

这是你的小提琴,更新:http://jsfiddle.net/ZcQM7/2/


如果你希望它是一个jQuery的方法,你就必须把它变成一个插件:

$.fn.animateIt = function() { 
    var $this = this; 
    this.slideToggle(5000, function() { 
     $this.animateIt(); 
    }); 
}; 

$("div#mover").animateIt();​ 

这是你的小提琴再次,与其他更新:http://jsfiddle.net/ZcQM7/1/

+0

非常感谢约瑟夫.. – Shiala

1

animateIt()是您在代码中声明并且不属于jQuery的函数。

您应该直接把它叫做:

function animateIt() { 
    return $("#mover").slideToggle(5000, animateIt); 
} 

animateIt();