为了简单起见,我删除了变量名称,只放入了值。
无法弄清楚为什么这不能正常工作,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 像素,触发 if 语句,滚动回小于 200 像素并触发 else 语句,但在任何时候都不会触发 else if 语句。
我认为这会是 - 满足条件 1,火灾 - 满足条件 2,火灾 - 满足条件 3,火灾?
最佳答案
您应该交换 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()
参数。
关于javascript - else if 语句在 jquery 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22824694/