If statement 区间函数中有许多if语句,其中一个有效,但更多的无效?
我的要求是每隔几秒钟我的div标签就会向左滑动(左边距) 我认为代码是自我解释的 有什么我遗漏的吗 这是因为众多的if语句吗 还是有更简单、更智能的功能If statement 区间函数中有许多if语句,其中一个有效,但更多的无效?,if-statement,intervals,If Statement,Intervals,我的要求是每隔几秒钟我的div标签就会向左滑动(左边距) 我认为代码是自我解释的 有什么我遗漏的吗 这是因为众多的if语句吗 还是有更简单、更智能的功能 setInterval(function(){ if ($(".carousel").css("margin-left")!='0%'){ $(".carousel").css("margin-left", "-100%"); } if ($(".carousel").css("margin-left")!='-100%
setInterval(function(){
if ($(".carousel").css("margin-left")!='0%'){
$(".carousel").css("margin-left", "-100%");
}
if ($(".carousel").css("margin-left")!='-100%'){
$(".carousel").css("margin-left", "-200%");
}
if ($(".carousel").css("margin-left")!='-200%'){
$(".carousel").css("margin-left", "-300%");
}
if ($(".carousel").css("margin-left")!='-300%'){
$(".carousel").css("margin-left", "-400%");
}
if ($(".carousel").css("margin-left")!='-400%'){
$(".carousel").css("margin-left", "-500%");
}
if ($(".carousel").css("margin-left")!='-500%'){
$(".carousel").css("margin-left", "-600%");
}
if ($(".carousel").css("margin-left")!='-600%'){
$(".carousel").css("margin-left", "-700%");
}
if ($(".carousel").css("margin-left")!='-700%'){
$(".carousel").css("margin-left", "0%");
}
}, 2000);
我怀疑你正在使用
=代码>而不是预期的=
此外,如果进行此更改,则必须正确地将if
语句链接到else if
中,否则,从0%
更改为-100%
将触发-100%
的if语句,然后再更改为-200%
,以此类推
另一方面,更简单的函数可能是:
由于下面的评论线程,此内容已更新。
function setCarouselMargin(marginLeft) {
$('.carousel').css('margin-left', marginLeft + '%');
marginLeft -= 100;
if (marginLeft < -700) {
marginLeft = 0;
}
setTimeout(function () { setCarouselMargin(marginLeft) }, 2000);
}
$(function() {
setCarouselMargin(0);
});
函数setCarouselMargin(marginLeft){
$('.carousel').css('margin-left',marginLeft+'%');
边际收益-=100;
如果(边际收益<-700){
marginLeft=0;
}
setTimeout(函数(){setCarouselMargin(marginLeft)},2000年);
}
$(函数(){
setCarouselMargin(0);
});
问题是我没有上下文可供使用。仅仅说“它不起作用”,我就不知道问题出在哪里。使用开发人员工具手动更改左边距是否如您所期望的那样有效?是的,这是上下文
此ul的宽度为父元素的800%。它应该每2秒滑动一次-向左滑动100%。在我的外部js:jQuery(document).ready(function(){setInterval(function(){var marginLeft=parseInt($('.carousel').css('margin-left'));marginLeft-=100;if(marginLeft<700){marginLeft=0;}$('.carousel').css('marginLeft',marginLeft+'%');},2000);});那if(marginLeft<700)
应该是if(marginLeft<-700)
。我已经做了一个有效的测试。它使用一个单独的函数来处理状态,因为在内部,左边距
被转换为一个像素值,打破了我上面的函数。是的,现在它移动了,第一张幻灯片看起来不错,然后直接弹到7,然后弹回到1