2013-08-26 139 views
0

由于某些原因,我的JavaScript一直没有正常工作。我隔离并清理了一切,但我坚持这一点。相反,然后试图找出它是什么造成了这一点(已经花了数小时),我决定找出一个更好的方法。毕竟,有不止一种方式来剥皮猫,对吧? 以下是我想要做的。有东西从0宽度,然后回到100%宽度。它的工作原理,但由于某些原因,它可以追溯到0在我的应用程序JQuery突然不能正常工作

的jsfiddle:http://jsfiddle.net/THnvz/2/

$(document).ready(function() { 
    $(".stretcher").each(function() { 
     $(".stretcher") 
      .data("origWidth", $(this).width()) 
      .width(0) 
      .animate({ 
      width: $(this).data("origWidth") 
     }, 2000); 
    }); 
}); 

只是寻找一个将工作更清洁更简单的方法。有什么建议么?

+2

foreach循环过多。 – Johan

+1

你可以发布一个jsFiddle来完成你的应用的功能吗? – j08691

+0

所以序列应该是100%> 0> 100%,或0> 100%> 0? –

回答

1

为此,您可以只用CSS3

更改您的CSS来:

.stretcher { 
    background-color:red; 
    width:100%; 
    height:10px; 
    animation: firstchange 2s linear; 
    -webkit-animation: firstchange 2s linear; 
    -moz-animation: firstchange 2s linear; 
} 

@keyframes firstchange 
{ 
0% {width:100%} 
50% {width:0} 
100% {width:100%} 
} 

@-webkit-keyframes firstchange /* Safari and Chrome */ 
{ 
0% {width:100%} 
50% {width:0} 
100% {width:100%} 
} 

@-moz-keyframes firstchange /* Firefox */ 
{ 
0% {width:100%} 
50% {width:0} 
100% {width:100%} 
} 

你不需要任何JavaScript。这应该工作

+0

css3 ftw!谢谢:) – goo

+0

是的css3总是:) – Tanuj

1

您应该在循环中始终使用$(this)

$(document).ready(function() { 
    $(".stretcher").each(function() { 
     var $this = $(this); 
     $this 
      .data("origWidth", $this.width()) 
      .width(0) 
      .animate({ 
       width: $this.data("origWidth") 
      }, 2000); 
    }); 
}); 

你的原代码彼此的宽度同时动画担架。

你也可以使用一个普通的变量,而不是保存宽度.data()

$(document).ready(function() { 
    $(".stretcher").each(function() { 
     var $this = $(this); 
     var orig_width = $this.width(); 
     $this 
      .width(0) 
      .animate({ 
       width: orig_width 
      }, 2000); 
    }); 
});