我已经提前为您制作了一个工作版本,并附有解释一切工作原理的评论。我还更正了HTML中的一些错误(多个元素不能具有相同的ID)。下面是JSfiddle:http://jsfiddle.net/e6r2e/1/。
HTML:
<div id="nav">
<div id="1" class="navitem activeSlide"><a>1</a></div>
<div id="2" class="navitem"><a>2</a></div>
<div id="3" class="navitem"><a>3</a></div>
<div id="4" class="navitem"><a>4</a></div>
<div id="5" class="navitem"><a>5</a></div>
</div>
<div id="arrow"></div>
CSS:
.navitem{
display:block;
float:left;
padding:10px 30px;
cursor:pointer;
}
.activeSlide{
background:#ccc;
}
.activeSlide a{
color:red;
}
#arrow{
width:10px;
height:10px;
background:black;
position:absolute;
margin-top:40px;
left:30px;
}
的JavaScript:
$(document).ready(function() {
var slideX = [30, 98, 166, 234, 302], //Define the x-position of the arrow for each slide
currentSlide = 0; //Current slide variable. Change this to change starting slide.
//Function to change slides. Accepts one parameter, the slide's jQuery object:
function changeSlide(slide) {
$('.activeSlide').removeClass('activeSlide'); //Remove previous slide's activeSlide class
$(slide).addClass('activeSlide'); //Add activeSlide class to current slide.
$('#arrow').clearQueue().animate({ //Animate the arrow to the correct location. clearQueue is used so that animations aren't stacked:
'left': slideX[currentSlide] + 'px' //Animate the 'left' selector (Better than margin-left).
}, 300); //Animation duration in milliseconds.
}
//Rotate through slides:
rotate = setInterval(function() {
//Check if we're on the last slide; if so, return to 0:
if (currentSlide + 1 >= slideX.length) {
currentSlide = 0;
} else {
currentSlide++;
}
//Call the changeSlide function with the slide's jQuery object as the parameter.
changeSlide($('#' + (currentSlide + 1)));
}, 5000); //Duration to stay on each slide in milliseconds.
//Animate to clicked slide:
$('.navitem').click(function() {
currentSlide = $(this).attr('id') - 1; //Change currentSlide variable to the slide clicked. We use the slide's ID to determine which slide it is, and then subtract one since we deal with numbers starting at 0, not 1.
changeSlide($(this)); //Call changeSlide function with the new slide's jQuery object as the parameter.
//Clear and restart our rotate interval so that the timer is reset. Otherwise if we clicked a slide with 1 second left on the timer, it would rotate again in 1 second instead of 5:
clearInterval(rotate);
rotate = setInterval(function() {
if (currentSlide + 1 >= slideX.length) {
currentSlide = 0;
} else {
currentSlide++;
}
changeSlide($('#' + (currentSlide + 1)));
}, 5000);
});
});
你可以张贴一些代码或作出的jsfiddle? – 2012-03-25 20:24:04
当然,检查我的线程编辑,也创建了一个基本的jsfiddle在这里:[链接](http://jsfiddle.net/mmmoustache/FSxMa/) – mmmoustache 2012-03-25 21:04:21