2010-10-21 90 views
1

我有下面的代码片段(见下文),并希望使功能切换 - 什么是最好的方式去做这个?jquery动画功能 - 使它切换

谢谢你。

<html> 
<head> 
    <title></title> 

<script type="text/javascript" src="js/jquery.js"></script> 

<script> 

$(document).ready(function() 
{ 
    $("#left_pane").css("left","-300px"); 
    $("#middle_pane").css("left","0px"); 

    //toggle the componenet with class msg_body 
    $(".toggle_right_pane").click(function() 
    {  
     $('#left_pane').animate({ 
     left: '0', 
     }, 500, function() { 
     // Animation complete. 
     }); 
     $('#main_pane').animate({ 
     left: '300', 
     }, 500, function() { 
     // Animation complete. 
     });   

    }); 
}); 

</script> 

<style> 

body{ 
    margin: 0; 
} 

#left_pane{ 
    float:left; 
    display:block; 
    width: 300px; 
    height: 100%; 
    overflow:hidden; 
    background: grey; 
    position:absolute; 
    z-index:1 
} 

#main_pane{ 
    float:left; 
    height:100%; 
    left:0px; 
    overflow:scroll; 
    position:absolute; 
    background: red;   
    right:0; 
} 


</style> 

</head> 

<body> 

    <div id="container"> 

     <div id="left_pane"> 
     menu 
     </div> 


     <div id="main_pane"> 
      <a class="toggle_right_pane" href="#">show/hide</a> 
     </div> 

    </div> 

</body> 
</html> 
+0

切换怎么样?像左右交换?喜欢来回穿过页面? – jcolebrand 2010-10-21 17:22:56

回答

10

您CA使用.toggle()两套功能之间切换,就像这样:

$(".toggle_right_pane").toggle(function() {  
    $('#left_pane').animate({ left: '0' }, 500); 
    $('#main_pane').animate({ left: '300' }, 500); 
}, function() {  
    $('#left_pane').animate({ left: '-300' }, 500); 
    $('#main_pane').animate({ left: '0' }, 500); 
}); 

You can test it out here


另外要小心你的标记,如果你把它看你现在有什么是这样的:

$('#left_pane').animate({ left: '0', }, 500, function() { }); 
            ^uh oh 

以上后面的逗号会使IE吹垫圈,所以要非常小心这些当你像你一样分手时。另外,如果你在回调函数中没有做任何事情,你可以把它关闭。

+0

太棒了!并感谢资源链接jsfiddle.com看起来令人惊叹! – Simon 2010-10-21 17:57:31

+0

@Simon - welcome :) – 2010-10-21 17:57:59

+0

这是一个很棒的演示,我尝试了很久以后的工作,然后我切换jsfiddle使用jQuery 1.10.1,它不再工作。有没有人知道使用'jquery-1.10.2.min.js'时的选择?编辑:它似乎工作,直到jQuery 1.8.3时,在jsfiddle中测试它。 – user1063287 2013-08-14 14:39:02

0

@ user1063287也许这样的事情,用不同的动画取决于是否活跃与否:

$(function() { 
     $("#left_pane").css("left","-300px"); 
     $("#main_pane").css("left","0px"); 
     $(".toggle_right_pane").addClass('active'); 

     $(".toggle_right_pane").click(function(e){ 
      e.preventDefault(); 
      if ($(this).hasClass("active")) { 
       $('#left_pane').animate({ left: '0' }, 500); 
       $('#main_pane').animate({ left: '300' }, 500);   
       $(this).removeClass("active"); 
      } else { 
       $('#left_pane').animate({ left: '-300' }, 500); 
       $('#main_pane').animate({ left: '0' }, 500); 
       $(this).addClass("active"); 
      } 
      return false; 
     }); 
}); 

fiddle