2013-08-17 68 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