Jquery使幻灯片自动播放
我已经做了一个小幻灯片,我正在尝试自动化它。Html元素如下所示:Jquery使幻灯片自动播放,jquery,slideshow,Jquery,Slideshow,我已经做了一个小幻灯片,我正在尝试自动化它。Html元素如下所示: <ul> <li> <h3 class="active-item" data-bg="background-image url">Title 1</h3> <div class="news-excerpt"><p>The excerpt</p></div> </li> <
<ul>
<li>
<h3 class="active-item" data-bg="background-image url">Title 1</h3>
<div class="news-excerpt"><p>The excerpt</p></div>
</li>
<li>
<h3 class="" data-bg="background-image url">Title 2</h3>
<div class="news-excerpt"><p>The excerpt</p></div>
</li>
<li>
<h3 class="" data-bg="background-image url">Title 3</h3>
<div class="news-excerpt"><p>The excerpt</p></div>
</li>
</ul>
现在我想让它自动运行,我每4秒运行一次。我怎样才能使它起作用:
$('html').addClass('js');
$(function() {
var timer = setInterval( showDiv, 3000);
function showDiv() {
// Select the next post to show
$(this) = $('#alternative-navigation div#last-posts-fadeshow h3.active-item').parent().next().find('h3');
// Get url of the background image to show.
var bgvar = $(this).attr("data-bg");
// Set the right post excerpt to show
$('.active-excerpt').removeClass('active-excerpt');
$(this).next('.news-excerpt').addClass('active-excerpt');
$('.active-item').removeClass('active-item');
$(this).addClass('active-item');
Cufon.refresh();
//alert (bgvar);
// Switch to right background image
$("#background-image-container").fadeTo('medium', 0.1, function()
{
$("#background-image-container").css("background-image", "url(" + bgvar + ")" );
}).fadeTo('medium', 1);
return false;
}
});
第一部分似乎选择了正确的标题,但什么也没有发生。有什么想法吗?$()
或jQuery()
不是一个变量,您不能使用$(this)='…'覆盖它代码>$()
是一个函数,它返回一组由选择器过滤的元素。见:
不要试图覆盖$(this)
,只需创建一个新变量,例如:
function showDiv() {
// Select the next post to show
var el = $('#alternative-navigation div#last-posts-fadeshow h3.active-item').parent().next().find('h3');
// Get url of the background image to show.
var bgvar = el.attr("data-bg");
// Set the right post excerpt to show
$('.active-excerpt').removeClass('active-excerpt');
el.next('.news-excerpt').addClass('active-excerpt');
$('.active-item').removeClass('active-item');
el.addClass('active-item');
Cufon.refresh();
//alert (bgvar);
// Switch to right background image
$("#background-image-container").fadeTo('medium', 0.1, function()
{
$("#background-image-container").css("background-image", "url(" + bgvar + ")" );
}).fadeTo('medium', 1);
return false;
}
要循环回到起点,这取决于您的HTML结构,但类似的东西应该可以工作
var el = $('#alternative-navigation div#last-posts-fadeshow h3.active-item').parent().next().find('h3');
if ( el.length == 0 )
el = $('#alternative-navigation div#last-posts-fadeshow').first().find('h3');
谢谢,我学到了一些东西:),这很有效。你知道当函数到达最后一个项时我如何选择第一个项吗?我添加了一些代码,可以为你指出正确的方向:)非常感谢,它与选择器“nextitem=$('#alternative navigation div#last posts fadeshow ul li:first child')配合得很好。find('h3');”
var el = $('#alternative-navigation div#last-posts-fadeshow h3.active-item').parent().next().find('h3');
if ( el.length == 0 )
el = $('#alternative-navigation div#last-posts-fadeshow').first().find('h3');