我在本教程中使用jQuery构建了一个Image Slider - https://www.youtube.com/watch?v=QtYP_eSVKfs。
我刚刚完成第二部分 - 构建自动图像幻灯片。结果应该是图像从1到4循环,然后在淡入和淡出时再次返回。
但是,当我加载页面时,第一张图片会淡入,但循环不会启动。第一张图像保留在显示屏上。
我猜它与我的startSlider功能有关,但我无法找到问题。我做错了什么?
HTML:
<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css">
<meta charset="utf-8">
<title>Slider</title>
</head>
<body>
<div class="wrapper">
<div id="slider">
<img id="1" src="images/image1.jpg">
<img id="2" src="images/image2.jpg">
<img id="3" src="images/image3.jpg">
<img id="4" src="images/image4.jpg">
</div>
<a href="#" class="left">Previous</a>
<a href="#" class="right">Next</a>
</div>
<script src="jquery.js"></script>
<script src="scripts.js"></script>
</body>
</html>
CSS:
#wrapper {
width: 600px;
margin: 0 auto;
}
#slider {
width: 600px;
height: 400px;
overflow: hidden;
margin: 30px auto;
}
#slider > img {
width: 600px;
height: 400px;
float: left;
display: none;
}
a {
padding: 5px 10px;
background-color: #F0F0F0;
margin-top: 30px;
text-decoration: none;
color: #666;
}
a.left {
float: left;
}
a.right {
float: right;
}
SCRIPT:
var sliderInt = 1;
var sliderNext = 2;
$(document).ready(function(){
$('#slider > img#1').fadeIn(300);
startSlider();
});
function startSlider() {
count = $('#slider > img').length();
if(sliderNext > count) {
sliderNext = 1;
sliderInt = 1;
}
loop = setInterval(function() {
$('#slider > img').fadeOut(300);
$('#slider > img#' + sliderNext).fadeIn(300);
sliderInt = sliderNext;
sliderNext = sliderNext + 1;
}, 3000);
}
答案 0 :(得分:0)
length
不是length()
,将if放在setInterval函数
var sliderInt = 1;
var sliderNext = 2;
$(document).ready(function() {
$('#slider > img#1').fadeIn(300);
startSlider();
});
function startSlider() {
count = $('#slider > img').length;
loop = setInterval(function() {
$('#slider > img').fadeOut(300);
$('#slider > img#' + sliderNext).fadeIn(300);
sliderInt = sliderNext;
sliderNext = sliderNext + 1;
if (sliderNext > count) {
sliderNext = 1;
sliderInt = 1;
}
}, 3000);
}
#wrapper {
width: 600px;
margin: 0 auto;
}
#slider {
width: 600px;
height: 400px;
overflow: hidden;
margin: 30px auto;
}
#slider > img {
width: 600px;
height: 400px;
float: left;
display: none;
}
a {
padding: 5px 10px;
background-color: #F0F0F0;
margin-top: 30px;
text-decoration: none;
color: #666;
}
a.left {
float: left;
}
a.right {
float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="wrapper">
<div id="slider">
<img id="1" src="http://lorempixel.com/400/200/">
<img id="2" src="http://lorempixel.com/400/200/sports/">
<img id="3" src="http://lorempixel.com/400/200/abstract/">
<img id="4" src="http://lorempixel.com/400/200/city/">
</div>
<a href="#" class="left">Previous</a>
<a href="#" class="right">Next</a>
</div>
答案 1 :(得分:0)
为了获得长度,你应该使用长度而不是长度()
count = $(&#39; #slider&gt; img&#39;)。length(); //错了
count = $(&#39; #slider&gt; img&#39;)。length; //正确