1

我正在尝试使用 jquery 使按钮打开另一个窗口。

该按钮应该能够打开窗口。然后应该使用相同的按钮来关闭窗口。我似乎遇到的问题是按钮打开窗口后没有设置我的变量。我对javascript和jquery真的很陌生,所以我不确定我是否做错了什么。

<html>
  <head>
   <script type="text/javascript" src="jquery.js"></script>
   <script type="text/javascript"> 
      var FileEdit = 0;
      $(document).ready(function(){
        if (FileEdit == 0)
        {
           $("button").click(function(){
             $("div").animate({opacity:0.4},"fast");
             $("div").animate({height:300,width:300},"slow");
             $("div").animate({opacity:1},"slow");
             FileEdit = 1;
           });
        }  
        if (FileEdit == 1)
        {
             $("button").click(function(){
                $("div").animate({height:000,width:000},"slow");
                FileEdit = 0;
             });
        }
      });
    </script> 
  </head>

     <body>
       <button>Start Animation</button>
       <br /><br />
       <div style="background:#98bf21;height:000px;width:000px;">
       </div>
    </body>
</html>

http://jsfiddle.net/tqpTE/

4

2 回答 2

3

jsFiddle 演示

var FileEdit = 0;

$("button").on('click', function(){

    // You only need one on('click') function
    // Test for FileEdit here & do whatever you need

    if (FileEdit === 0) { 

        // Also having those 3 animations right in a row won't make them
        // go one - after - another. You need to use callback functions
        // to start the next animation after the previous one finished.

        $("div").animate({opacity:0.4},"fast", //callback1
            function () { $(this).animate({height:300,width:300},"slow", //callback2
                function () { $("div").animate({opacity:1},"slow"); }
            )}
        );
        FileEdit = 1;
    }

    else { 
         $("div").animate({height:000,width:000},"slow");
         FileEdit = 0;
    }
});

有关 .animate() 回调函数的更多信息

于 2012-08-23T17:31:44.517 回答
1

您的条件需要在每次点击时运行 - 而不是一次,在 DOM 准备好时,就像目前一样。另请注意,您的代码可以大大减少为以下内容:

var fileEdit = 0;
$(function(){
    $("button").on('click', function() {
        var anim_data = !fileEdit ? {width: 300, height: 300} : {width: 0, height: 0};
        $("div").animate(anim_data, 'slow');
        fileEdit = !fileEdit ? 1 : 0;
    });
});

几点注意事项:

1) 您似乎对不透明度进行了两次动画处理(一次为 0.4,同时为 1),因此,出于本演示的目的,我完全删除了对它的引用。

fadeIn()2) 除非您需要将动画设置为部分不透明度(而不是 0 或 1),否则使用 jQuery和fadeOut()方法会更容易。

3) 设置width: 000width: 0

4) 避免在 var 名称中使用大写字母 - 大写字母通常用于表示构造函数。

5)使用双等号测试0和值时要小心,因为真值/假值的概念会让你感到惊讶。在不确定的情况下,使用not进行测试总是最安全的。1=====

6) 虽然没click问题,但 jQuery 1.7 引入了对其混乱事件 API 的整理,因此您现在可以使用on()and off(). click()和其他只是在幕后委托给on().

于 2012-08-23T17:36:17.730 回答