mousewheel和if语句jquery

时间:2016-09-04 15:44:15

标签: javascript jquery html scroll mousewheel

我想要做的就是当你尝试向上或向下滚动它时调用一个改变页面的功能。我的身体有overflow:hidden

我正在使用名为https://github.com/jquery/jquery-mousewheel'>mousewheel的jquery插件

这是我的代码:

$('#body').on('mousewheel', function(event) {

  if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) {
    //scroll down
    if(document.getElementById('pgcount').innerHTML == 'Page 1') scrollDown(2);
    if(document.getElementById('pgcount').innerHTML == 'Page 2') scrollDown(3);
    if(document.getElementById('pgcount').innerHTML == 'Page 3') scrollDown(4);
    if(document.getElementById('pgcount').innerHTML == 'Page 4') scrollDown(5);
  } else {
    //scroll up
    if(document.getElementById('pgcount').innerHTML == 'Page 2') scrollUp(1);
    if(document.getElementById('pgcount').innerHTML == 'Page 3') scrollUp(2);
    if(document.getElementById('pgcount').innerHTML == 'Page 4') scrollUp(3);
    if(document.getElementById('pgcount').innerHTML == 'Page 5') scrollUp(4);
  }
  //prevent page fom scrolling
  return false;

});

出于某种原因,它在向上滚动时有效但向下滚动时会直接进入第5页(最后一个)。当我向每个if语句添加console.log(document.getElementById('pgcount').innerHTML)以向下滚动时,记录了这个:

Page 1
Page 2
Page 3
Page 4

我不明白为什么它会向上滚动而不是向下滚动。我知道被调用的函数(scrollDown)不是问题,因为它从控制台调用时可以正常工作。

提前致谢

1 个答案:

答案 0 :(得分:0)

假设scrollDown()函数改变了页面值,解决方案非常明确:

if(document.getElementById('pgcount').innerHTML == 'Page 1') scrollDown(2);
if(document.getElementById('pgcount').innerHTML == 'Page 2') scrollDown(3);
if(document.getElementById('pgcount').innerHTML == 'Page 3') scrollDown(4);
if(document.getElementById('pgcount').innerHTML == 'Page 4') scrollDown(5);

如果您在第1页,则代码调用scrollDown(2),将您移至第2页。然后代码会立即检查您是否在第2页,如果是,则滚动到第3页。重复此过程,直至到达第5页。

如果您明确跟踪页面而不是查看页面文本,那么事情会更加清晰。但是,最简单的方法是添加else

if(document.getElementById('pgcount').innerHTML == 'Page 1') scrollDown(2);
else if(document.getElementById('pgcount').innerHTML == 'Page 2') scrollDown(3);
else if(document.getElementById('pgcount').innerHTML == 'Page 3') scrollDown(4);
else if(document.getElementById('pgcount').innerHTML == 'Page 4') scrollDown(5);