您好我正在尝试使用按钮制作响应式滑块。滑块应该能够一次装载一个4个面板。在java脚本中设置了一个计时器功能,可在4秒后移动每个div。没有一个按预期工作!如果可以,请帮忙。
我的HTML是:
<link rel="stylesheet" type="text/css" href="slider.css">
<script type='text/javascript' src='jquery-1.11.2.min.js'> </script>
<script type='text/javascript' src='jquery-ui.min.js'> </script>
<script src='slider.js'> </script>
<div class="slide-viewer">
<div class="slide-group">
<div class="slide slide-1">Hello</div>
<div class="slide slide-2">he2llo</div>
<div class="slide slide-3">he3llo</div>
<div class="slide slide-4">g4ello</div>
</div>
</div>
<div class="slide-buttons"> </div>
</html>
我的CSS是
.slide-viewer {
position: relative;
overflow:hidden;
height: 300px;
background-color:green;
color: white;
}
.slide-group {
width: 100%;
height: 100%;
position: relative;
}
.slide {
width:100%;
height:100%;
display:none;
position:absolute;
}
.slide:first-child {
display:block;
}
我的JavaScript是:
$('.slider').each(function(){
var $this = $(this);
var $group = $this.find('.slide-group');
var $slides = $this.find('.slide');
var buttonArray = [];
var currentIndex = 0;
var timeout;
function move(newIndex){
var animateLeft, slideLeft;
advance();
if($group.is(':animated') || currentIndex === newIndex) {
return;
}
buttonArray[currentIndex].removeClass('active');
buttonArray[newIndex].addClass('active');
if(newIndex > currentIndex) {
slideLeft = '100%';
animateLeft = '-100%';
} else {
slideLeft = '-100%';
animateLeft = '100%';
}
$slides.eq(newIndex).css( {left:slideLeft, display:'block'} );
$group.animate( {left: animateLeft} , function(){
$slides.eq(currentIndex).css( {display:'none'} );
$slides.eq(newIndex).css( {left:0} );
$group.css( {left:0} );
currentIndex = newIndex;
});
}
function advance() {
clearTimeout(timeout);
timeout = setTimeout(function(){
if(currentIndex < ($slides.length - 1)) {
move(currentIndex + 1);
} else {
move(0);
}
},4000);
}
$.each($slides, function(index){
var $button = $('<button type="button" class="slide-btn">•</button>')
if (index === currentIndex) {
$button.addClass('active');
}
$button.on('click', function(){
move(index);
}).appendTo('.slide-buttons');
buttonArray.push($button);
});
advance();
});
答案 0 :(得分:2)
您的代码正在尝试使用“滑块”类作为滑块来检测所有元素,但我在HTML中看不到这样的元素。如果用<div class="slider"> ... </div>
包围滑块的元素,它就可以工作。
<div class="slider">
<div class="slide-viewer">
<div class="slide-group">
<div class="slide slide-1">Hello</div>
<div class="slide slide-2">he2llo</div>
<div class="slide slide-3">he3llo</div>
<div class="slide slide-4">g4ello</div>
</div>
</div>
<div class="slide-buttons"></div>
</div>