1

我正在尝试使用 jQuery 制作一个简单的动画。我尝试在外部(外部文件)和内部(在脚本标签内)添加脚本。我已经测试了页面是否使用警报功能识别脚本,但脚本没有执行。我认为这与语法有关。

$("#container5").hover(function() {
        //hover in
        $(#container5).animate({
            height: "250",
            width: "250",
            left: "-=50",
            top: "-=50",
            }, "fast");
            }, function() {
            //hover out
            $(#container5).animate({
            height: "200",
            width: "200",
            left: "+=50",
            top: "+=50",
            }, "fast");
        }
    })(jQuery);
4

3 回答 3

0

除了不在准备好的处理程序中之外,您的语法有点偏离:

1:您的#container 需要始终用引号括起来 例如:$('#container5') - 或者您可以在悬停动画上使用 $(this),因为它位于同一个容器上

2:top 后面多了一个逗号:“+=50”——把它去掉。动画的最后一行或 {} 中的任何内容不能以逗号结尾。

3:把它放在一个就绪函数中。

这是更新的代码:

$(document).ready(function(){
    $("#container5").hover(
    function() {
        $(this).animate({height: "250", width: "250", left: "-=50", top: "-=50"}, "fast");
    }, 
    function() {
        $('#container5').animate({height: "200", width: "200", left: "+=50", top: "+=50"}, "fast");
    });
});

请注意:我使用了 $(this) 和 $('#container5')。在这种情况下,您可以互换使用这两者。 如果您想了解更多动态事件,请阅读 $(this) 。

于 2012-12-14T23:13:35.540 回答
0

You need to wrap your code in a ready function. The problem is your jQuery is running beofre the DOM is ready. This will work.

jQuery(document).ready(function($){
    $('#container5').animate({
       height: "250",
       width: "250",
       left: "-=50",
       top: "-=50"
    }, "fast");
});
于 2012-12-14T23:06:38.550 回答
0

You need to wrap your code in a ready handler, plus you also need to wrap your strings with quotes.

You also seem to have a broken function set-up as Hellion has stated, you shouldn't be passing jQuery into a function at the point you are doing. Instead you need to be wrapping all your code in an annonymous function, with a $ as a param, and pass jQuery into that. This is so as to protect against other libraries that may make use of a global $ var.

Three things that will help you detect these problems in future.

  • be specific with your indenting. This will highlight problems much more easily.
  • Use a text editor with syntax/code highlighting - this will show you that your strings are wrong.
  • check your error console in which ever browser you use, this would have given you some hints as to the illegal syntax layout.

The following should fix your issues:

;(function($){
  $(function(){
    $('#container5').hover(
      function(){
        $('#container5').animate({
          height: "250",
          width: "250",
          left: "-=50",
          top: "-=50",
        },"fast");
      },
      function() {
        $('#container5').animate({
          height: "200",
          width: "200",
          left: "+=50",
          top: "+=50",
        },"fast");
      }
    );
  });
})(jQuery);
于 2012-12-14T23:07:33.227 回答