我试图通过在.css({"left" : "0px"})
上设置ul.slider-ul
来让以下滑块循环播放。我有一个console.log("Loop")
要检查if
语句是否有效。
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
值来创建循环操作。
答案 0 :(得分:-1)
你遗失了很多&#39 ;;&#39;在您的JavaScript代码中:
这是一个有效的代码:( DEMO JSFiddle)
function slider(x) {
var rand = Math.round(Math.random() * (5000 - 1000)) + 1000;
// go to left
setTimeout(function () {
var size = x.parent().width();
var futureLoc = x.offset().left + x.outerWidth(true) - size;
var parentLoc = x.parent().offset().left;
if (futureLoc <= parentLoc) {
console.log("Loop");
x.animate({
"left": "0px"
},function(){slider(x);});
} else {
x.animate({
"left": "-=" + size + "px"
}, 2000,function(){slider(x);});
}
}, rand);
}
$("ul.slider-ul").each(function () {
slider($(this));
});
我必须改变很多东西,并且在重置之前动画是空的,所以你必须玩它才能拥有完美的动画。