2013-08-17 36 views
0
<script> 

    var swidth = $(window).width(); 
    var sheight = $(window).height(); 

    $(document).ready(function(){ 


     $("#box").animate({ //animates depending on screen size 

      top: (sheight*0.22)+"px", 
      left: (swidth*0.25)+"px", 
      width:(swidth*0.3)-40+"px", 
      height: (sheight*0.35)-40+"px", 

     }, 2000, function(){ 

      $('<input type="button" value="My button">').appendTo(this) 
      .click(function(){ 

       $(this).animate({ // reverses animation back to original size and location 


       top: "150px", 
       left: "100px", 
       width:"1px", 
       height: "1px", 

       }, 2000,) 

      }); 
     }); 


    }); 

</script> 

如果我更换后工作...jQuery的动画不会点击

  $(this).animate({ // reverses animation back to original size and location 


      top: "150px", 
      left: "100px", 
      width:"1px", 
      height: "1px", 

      }, 2000,) 

...与...

alert("You clicked me!"); 

...它的工作原理。所以错误在反向动画的某处。但是哪里?提前感谢任何答案!

回答

1

好像有2个问题在这里

  1. 额外的语法问题,
  2. 您设置动画的错误的元素,在注册到按钮this指向点击按钮单击处理程序,但你需要动画#box元素是按钮的父元素

尝试

$(document).ready(function(){ 
    $("#box").animate({ 
     top: (sheight*0.22)+"px", 
     left: (swidth*0.25)+"px", 
     width:(swidth*0.3)-40+"px", 
     height: (sheight*0.35)-40+"px", 
    }, 2000, function(){ 
     $('<input type="button" value="My button">').appendTo(this).click(function(){ 
      $(this).parent().animate({ //you need to animate the parent element #box, here this is the button you clicked 
       top: "150px", 
       left: "100px", 
       width:"1px", 
       height: "1px", 
      }, 2000) //additional , here 

     }); 
    }); 
}); 
+0

万分感谢。完美工作。我明白你的意思了。我尝试用''#box'替换'this',代码不起作用,你知道为什么吗? '(this).parent()'与'(“#box”)'不一样吗? –

+0

@DennisCallanan它应该工作'$('#box')'而不是'$(this).parent()' –

+0

嗯..它现在真的有效。我觉得很奇怪。感谢那。 –

1

你已经在你的animate方法得到了流氓“”。你是对的,现在得到这个错误,如果你现在检查您的控制台:

Uncaught SyntaxError: Unexpected token) 

变化:

}, 2000,) //last line of the animate method 

}, 2000) 

height: "1px", 

height: "1px" 

如果你正在试图与ID box动画后面的元素,你会更好保持你的clickanimate,像这样:

$("#box").on("click", "input[type=button]", function() { 
    $(this).parent("#box").animate({ //use parent 
     top: "150px", 
     left: "100px", 
     width: "1px", 
     height: "1px" 
    }, 2000); 
}); 

然后,在回调,

$('<input type="button" value="My button">').appendTo(this); 
+0

谢谢。我其实是有它的权利,但原来它改变了认为这可能是问题 –

+0

hmmm..also你需要使用'父()',使之成为'工作#box' – krishgopinath