2012-04-06 130 views
-1

这里jQuery的开关类是什么,我想发生:后的动画不能正常工作

用户应该点击一个链接/按钮,将动画,虽然动画所显示的DIV当前没有显示到屏幕上一个div在屏幕之外。

问题:

我的代码将动画的div进出但从.notcurrent类不会改变.current,反之亦然。

HTML:

<button id="R">Click 1</button> 
<button id="G">Click 2</button> 
<button id="B">Click 3</button> 

<div id="box"> 
    <div id="one" class="current"> 
    </div> 
    <div id="two" class="notcurrent"> 
    </div> 
    <div id="three" class="notcurrent"> 
    </div> 
</div> 

JS:

var panel1 = $('#one'); 
var panel2 = $('#two'); 
var panel3 = $('#three'); 

var current = $('.current'); 
var notcurrent = $('.notcurrent'); 

var cTop = current.css('top'); 
var nTop = notcurrent.css('top'); 

var button1 = $('#R'); 
var button2 = $('#G'); 
var button3 = $('#B'); 

button1.click(function() { 
    if (panel1.css('top') === '500px') { 
     current.animate({ 
      top: "500px" 
     }).attr("class", notcurrent); 

     panel1.animate({ 
      top: "0px" 
     }).attr("class", current); 
    } 
}); 

button2.click(function() { 
    if (panel2.css('top') === '500px') { 
     current.animate({ 
      top: "500px" 
     }).attr("class", notcurrent); 

     panel2.animate({ 
      top: "0px" 
     }).attr("class", current); 
    } 
}); 

button3.click(function() { 
    if (panel3.css('top') === '500px') { 
     current.animate({ 
      top: "500px" 
     }).attr("class", notcurrent); 

     panel3.animate({ 
      top: "0px" 
     }).attr("class", current); 
    } 
}); 

活生生的例子:http://jsfiddle.net/bz6cH/20/

是否有人可以找出是什么原因造成的问题,如果有一个更好的如何编码我想要的?

+1

安置自己在这里的代码,不只是在不同的网站。 – 2012-04-06 01:19:34

+0

@ tw16,感谢您通过添加代码来编辑问题..我甚至不知道您可以这样做。 – 2012-04-06 01:27:15

回答

0

这是你想要的吗?

var panel1 = $('#one'); 
var panel2 = $('#two'); 
var panel3 = $('#three'); 

var current = $('.current'); 
var notcurrent = $('.notcurrent'); 

var cTop = current.css('top'); 
var nTop = notcurrent.css('top'); 

var button1 = $('#R'); 
var button2 = $('#G'); 
var button3 = $('#B'); 

button1.click(function() { 
    if (panel1.css('top') === '500px') { 
     $('.current').animate({ 
     top: "500px" 
     }).attr("class", "notcurrent"); 

     panel1.animate({ 
     top: "0px" 
     }).attr("class", "current"); 
    } 
}); 

button2.click(function() { 
    if (panel2.css('top') === '500px') { 
     $('.current').animate({ 
     top: "500px" 
     }).attr("class", "notcurrent"); 

     panel2.animate({ 
     top: "0px" 
     }).attr("class", "current"); 
    } 
}); 

button3.click(function() { 
    if (panel3.css('top') === '500px') { 
     $('.current').animate({ 
     top: "500px" 
     }).attr("class", "notcurrent"); 

     panel3.animate({ 
     top: "0px" 
     }).attr("class", "current"); 
    } 
});​ 
+0

这是一个问题或答案?你做了什么来改进代码? – 2012-04-06 01:17:23

+0

它看起来与我使用的代码没有任何区别,你有什么改变吗? – 2012-04-06 01:22:09

+0

哦,是的,这有效,但我仍然不知道你改变了什么,为什么修复它? – 2012-04-06 01:25:59

0

我认为你有两件事情没有奏效。首先,您尽早创建一个变量来保存当前的div,但这不会在您的点击处理程序中重新评估;它总是会引用同一个div。其次,你在不删除“notCurrent”类的情况下添加“当前”类,反之亦然。这里有一个修正版本:

http://jsfiddle.net/33D8c/