我试图通过在ul.slider-ul
上设置.css({"left" : "0px"})
来获得以下滑块。我有一个console.log("Loop")
去检查if
声明正在工作,它是。jQuery循环滑块问题
HTML
<div class="slider-small-box sone slider-box">
<ul class="slider-ul">
<li>
<img src="spacer.gif" class="slider-img">
</li>
<li>
<img src="spacer2.gif" class="slider-img">
</li>
<li>
<img src="spacer2.gif" class="slider-img">
</li>
<li>
<img src="spacer2.gif" class="slider-img">
</li>
</ul>
</div>
CSS
.slider-box {
overflow: hidden;
position: relative;
}
.slider-box ul {
padding: 0px;
margin: 0px;
white-space: nowrap;
position: absolute;
left: 0px;
right: auto;
}
.slider-box > ul > li {
display: inline-block;
border-radius: 5px;
}
.slider-small-box > ul > li > img {
width: 270px;
height: 200px;
background-color: #333333;
border-radius: 5px;
}
.slider-large-box > ul > li > img {
width: 550px;
height: 200px;
background-color: #333333;
border-radius: 5px;
}
jQuery的
function slider(x) {
function loop() { //Sets repeating random value
var rand = Math.round(Math.random() * (5000 - 1000)) + 1000;
slider(x)
}
var size = $(x).parent().width() //Getting the size of the viewport div
var rand = Math.round(Math.random() * (5000 - 1000)) + 1000; //Sets initial random value
setTimeout(function() { //Animating the slider to the left with a random time
$(x).animate({"left" : "-=" + size + "px"}, 2000)
loop();
}, rand);
var width = 0;
$(x).find('li').each(function() { //Finding the total width of the images
width += $(this).outerWidth(true);
return(width)
});
var offset = size - width + "px"; //The point at which to reset the slider
var pos = $(x).position().left + "px"; //The current left position of the slider
var $this = $(this)
if(pos == offset) {
console.log("Loop"); //This gets called out
$this.animate({"left" : "0px"}); //This doesn't set the css value
};
}
$(function() {
$("ul.slider-ul").each(function() {
$this = $(this)
slider($this)
});
});
在这里看到的小提琴:Jsfiddle
编辑:
澄清问题是jQuery底部的if语句。出于某种原因,它不会重置元素的css的left
值以创建循环操作。
您的问题是什么? – Apolo
@Apolo我的问题是循环'if'语句不工作('if(pos == offset){}')。滑块继续向左移动。 – Mallander