如何使用jquery逐个显示和隐藏每个div

我想创建一个flash新闻标题。
但我不知道问题出在哪里! 🙁
(因为我是网页设计初学者:D)
所以…

我想创建一个标题的一部分,显示(淡入)一个标题和隐藏(fadeOut)延迟…
之后显示下一个标题……(在一个没有停止的循环中)!

PLZ帮助我学习如何创建……:这些是我写的代码:

This is news title 1
This is news title 2
This is news title 3
This is news title 4
This is news title 5
This is news title 6
This is news title 7
$(document).ready(function() { $('.news').each(function(index) { $(this).fadeIn('slow').delay(700).fadeOut('slow'); }); });

你可以试试这个。

它不是那么专业的代码,但应该工作。

这是jsFiddle解决方案:

http://jsfiddle.net/migontech/sfUU6/

 var news = $('.news') current = 0; news.hide(); Rotator(); function Rotator() { $(news[current]).fadeIn('slow').delay(500).fadeOut('slow'); $(news[current]).queue(function() { current = current < news.length - 1 ? current + 1 : 0; Rotator(); $(this).dequeue(); }); } 

编辑

这是变量的声明。 重要的是,你可以看到我在开始时选择了jQuery并将其分配给变量。 原因是因为如果要在代码的每一行中使用此选择器,并调用$('。news')。dosomthing()然后$('。news')。dosomethingelse(),jQuery将搜索每次调用它时,这些元素的DOM都是。 现在它将会做一次。 而且因为你正在使用类选择器,所以这是一个非常慢的选择器,你不必每次都这样做,赢得性能。 你可能不会注意到它但仍然。 🙂

 var news = $('.news') current = 0; 

然后我们隐藏所有元素并开始第一次旋转。

 news.hide(); Rotator(); 

现在,您可能对Rotator()函数有更多疑问。 在这里你可以看到我保留了你原来的fadeIn和fadeOut代码,但是我把它放在一个函数中,只将它应用到当前选中的元素。 我添加的是一个jQuery.queue(),它只会添加一个队列并等待上述所有效果完成后再执行代码。

我们只增加索引('当前'变量)或者如果它高于所选元素的长度则重新设置为0,并再次为当前索引调用Rotator()。 并且不要忘记在末尾使用.dequeue()来告诉队列可以被删除并继续。

 function Rotator() { $(news[current]).fadeIn('slow').delay(500).fadeOut('slow'); $(news[current]).queue(function() { current = current < news.length - 1 ? current + 1 : 0; Rotator(); $(this).dequeue(); }); } 

你为每个li设置相同的延迟。

尝试

 $('.news').each(function(index,i) { $(this).delay(index * 1001).fadeIn('slow').fadeOut('slow'); }); 

演示

以下代码将旋转新闻……

   
This is news title 1
This is news title 2
This is news title 3
This is news title 4
This is news title 5
This is news title 6
This is news title 7