点击后jQuery动画将无效

时间:2013-08-17 10:15:54

标签: jquery css button jquery-animate

<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>

如果我替换......

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


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

            }, 2000, )

...与...

alert("You clicked me!");

......它有效。所以错误是在某个地方的反向动画中。但是哪里?谢谢你提前给出任何答案!

2 个答案:

答案 0 :(得分:1)

你的animate方法中有一个流氓“,”。如果你现在检查你的控制台,你现在就会收到这个错误:

Uncaught SyntaxError: Unexpected token ) 

更改:

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

}, 2000)

height: "1px",

height: "1px"

如果您尝试将ID为box的元素设置回动画,那么最好将click保留在animate之外,如下所示:

$("#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);

答案 1 :(得分:1)

这里似乎有两个问题

  1. extra的语法问题,
  2. 您正在设置错误元素的动画,在注册到按钮this的点击处理程序中指向单击的按钮,但您需要为#box元素设置动画,该元素是按钮的父元素
  3. 尝试

    $(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
    
            });
        });
    });