创建功能以一直向下滑动div

时间:2013-01-02 21:00:22

标签: javascript-events

我正在尝试构建一个可以向下滑动特定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>

但它给了我这个错误“Uncaught TypeError:Object [object Object]没有方法'animateIt'”

Here's a fiddle

提前致谢。希亚...

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:1)

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

你应该直接打电话:

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

animateIt();