为了简单起见,我删除了变量名,并将值放入其中。
无法解释为什么这不能正常工作,else语句工作得很好,if语句工作得很好,但是else if部分不工作。
if (scrollTop > 200) {
$('.vote-next-hover').css({
position: 'fixed',
top: '50px',
width: statuscontain,
});
}
else if (scrollTop > 5500) {
$('.vote-next-hover').css({
position: 'absolute',
top: '',
width: '',
});
}
else {
$('.vote-next-hover').css({
position: 'relative',
top: '',
width: '',
});
} 滚动200 no,触发if语句,滚动回滚到小于200,它会触发else语句,但在任何时候它都不会触发else if语句。
我想应该是-条件1满足,火灾-条件2满足,火灾-条件3满足,火灾?
发布于 2014-04-02 23:00:38
您应该交换if和else if子句。要知道,如果scrollTop值大于5500,那么它肯定比200大-因此它将很好地通过第一个检查,从而使第二个检查变得毫无意义。
因此,if (scrollTop > 5500)应该放在代码的第一位,然后是else if (scrollTop > 200)检查。
我想知道你知道同样的分支逻辑可以用.switch
var hoverStyle = { position: 'relative', top: '', width: '' };
switch (true) {
case scrollTop > 5500:
hoverStyle.position = 'absolute';
break;
case scrollTop > 200:
hoverStyle = { position: 'fixed', top: '50px', width: statuscontain };
}
$('.vote-next-hover').css(hoverStyle);有些人甚至认为它比if-elseif-else更具可读性。当然,同样的限制也适用于此--不太常见的情况应该先处理(或者以后再检查)。
作为一个副手,我真的认为在分支中复制$('.vote-next-hover').css()调用是没有意义的。只需要分离代码的不同部分就足够了--在本例中,设置.css() param。
发布于 2014-04-02 23:04:45
if/else if/else块应该只运行这三种选择中的一种。例如:
var test = 4;
if (test === 4) { //true
test = 3;
} else if(test === 3) {//does not do, already did one
test = 0
} else {
test = “something”
}因此,您需要三个if块,而不是if/else /else。
发布于 2014-04-02 23:03:57
假设你已经滚动到6000,6000是大于200,所以第一个条件就满足了。然后,因为您有一个else if,所以它不会测试第二个条件。
你有两个选择:
将scrollTop > 5500检查添加到> 200检查中,或者替换if, else if的顺序,首先放置> 5500检查,然后再> 200检查。
if (scrollTop > 200) {
if (scrollTop > 5500) {
$('.vote - next - hover ').css({
position: 'absolute ',
top: '',
width: '',
});
} else {
$('.vote - next - hover ').css({
position: 'fixed ',
top: '50px ',
width: statuscontain,
});
}
} else {
$('.vote - next - hover ').css({
position: 'relative ',
top: '',
width: '',
});
}https://stackoverflow.com/questions/22824694
复制相似问题