我只是想基于margin-left css属性做简单的滑块,但它看起来结果不会在部分margin-left增量之间呈现。我的代码出了什么问题?
https://jsfiddle.net/1utkr6et/
HTML:
<div class="main-padding">
<div id="wrapper-slider">
<div class="item-slider item-slider1"></div>
<div class="item-slider item-slider2"></div>
<div class="item-slider item-slider3"></div>
</div>
</div>
的CSS:
* {
border: 0;
margin: 0;
padding: 0;
outline: 0;
}
a {
text-decoration: none;
color: inherit;
}
body {
font-size: 62.5%;
}
ul, ol {
list-style-type: none;
}
.main-padding {
padding: 20px;
}
#wrapper-slider {
height: 200px;
position: relative;
overflow: hidden;
}
.item-slider {
width: 100%;
float: left;
height: 100%;
}
.item-slider1 {
background-color: red;
}
.item-slider2 {
background-color: blue;
}
.item-slider3 {
background-color: yellow;
}
JS(jquery的):
$(function () {
var item = ".item-slider";
var next = 1;
setInterval(function() {
$(item + next).animate({"marginLeft": "-100%"}, 1000);
next++;
}, 2000);
});
答案 0 :(得分:1)
滑块的主要问题是您正在定义滑块float
的元素。我已对您的代码进行了一些更改,以使其正常工作。
<强> CSS:强>
.item-slider {
position: absolute;
left: 100%;
width: 100%;
height: 100%;
}
<强> JavaScript的:强>
$(function () {
var item = ".item-slider";
var next = 1;
var current;
setInterval(function() {
if(next === 1){
prev = $(item + 3);
}else{
prev = $(item + (next - 1));
}
current = $(item + next);
current.css({"left": "100%"});
current.animate({"left": "0"}, 1000);
prev.animate({"left": "-100%"}, 1000);
if(next === 3){
next = 1;
}else{
next++;
}
}, 2000);
});
答案 1 :(得分:1)
您需要为包装滑块指定宽度,例如每张幻灯片width:300%;
100%。但是,padding
的{{1}}会使幻灯片变得非常困难,因为它们彼此相邻,因此您可以看到下一张幻灯片的大约20px。除非有更好的方法,我建议不要使用我在演示中的填充。
您还需要计算每个幻灯片宽度。
<强>演示强>
https://jsfiddle.net/twgvxj1z/
<强>代码强>
main-padding