使用固定数量的像素滚动页面并使用滚轮

时间:2017-10-05 08:06:17

标签: javascript angular

我有一个元素列表,我想使用滚轮从一个移动到另一个,但问题是我无法使鼠标滚轮滚动具有固定像素数量的页面。 我试图在Angular2中做到这一点,但纯JavaScript解决方案也会有所帮助。我的代码如下所示:

@HostListener('window:scroll', ['$event'])
  onWindowScroll(e) {
    e.preventDefault();
    const st = window.pageYOffset;
    if (st > this.lastScrollTop) {
        this.goToNext();
    } else {
        this.goToPrevious();
    }
    this.lastScrollTop = st;
  }

goToNext = () => {
    window.scrollBy(0, 210);
}

goToPrevious = () => {
    window.scrollBy(0, -210);
}

此实现的问题是每次滚动页面时都会多次调用goToNext()goToPrevious()函数。所以我试图阻止默认的滚动事件,然后使用window.scrollBy(x, y)滚动(使用固定数量的像素)页面。 我可以使用goToNext()goToPrevious()从一个项目导航到另一个项目,并使用键盘上的向上和向下箭头,购买我需要使用鼠标滚轮。谢谢!

UPDATE :更具体一点:当我从鼠标滚轮向下滚动时,我希望页面以精确的像素数滚动(现在为210)。因此,即使我更加努力地滚动,或正常滚动,或者以任何其他方式滚动,我都需要使用相同数量的像素滚动页面。然后,在另一个滚动页面上,页面应该再次滚动210px。想法是让项目始终在页面上的相同位置。此时,当我滚动时,会发生许多滚动事件,因此我的滚动函数goToNext()goToPrevious()被多次调用(每个滚动事件一次),页面基本上滚动到底部它的。

我试图复制他们在这里的行为:

  

https://admin.typeform.com

从模板(注册表单)创建新表单时。他们没有完全符合我想要达到的目标,但我正在努力实现这一目标'滚动'欺骗,以避免同时有2个项目处于非活动状态。

1 个答案:

答案 0 :(得分:1)

这就是我要做的事,

我会为keydownmousewheel事件附加一个监听器,然后从那里停止默认的滚动调用preventDefault。然后根据事件指向的方向调用函数scrollDownscrollUp

您可以e.deltaY使用onwheele.key使用onkeydown

以下是一个示例代码段。当然,添加平滑的滚动效果是你的任务。

window.onwheel = beforeScroll;
window.onkeydown = beforeScroll;
var scrollVal = 0;
function beforeScroll(e) {
    if (e.type == 'wheel') {
        if (e.deltaY < 0) {
            scrollUp();
        } else {
            scrollDown();
        }
    }
    else if (e.type == 'keydown' && (e.key == 'ArrowDown' || e.key == 'ArrowUp')) {
        if (e.key == 'ArrowDown')
            scrollDown();
        else if (e.key == 'ArrowUp')
            scrollUp();
    }

    e.preventDefault();
    return;
}

function scrollUp() {
    if (scrollVal > 0)
        scrollVal -= 200;

    this.scroll(0, scrollVal);
}

function scrollDown() {
    if (scrollVal < document.body.scrollHeight)
        scrollVal += 200;
    //should detect for maximum scroll
    this.scroll(0, scrollVal);
}
.demo {
  width: 100%;
}

.demo .content:nth-child(odd) {
  background-color: grey;
}

.content {
  width: 100%;
  height: 200px;
  background-color: white;
  border: solid 1px black;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="demo">
  <div class="content"><h1>1</h1></div>
  <div class="content"><h1>2</h1></div>
  <div class="content"><h1>3</h1></div>
  <div class="content"><h1>4</h1></div>
  <div class="content"><h1>5</h1></div>
  <div class="content"><h1>6</h1></div>
  <div class="content"><h1>7</h1></div>
  <div class="content"><h1>8</h1></div>
  <div class="content"><h1>9</h1></div>
</div>