Aurelia 打字稿滚动到页面顶部

Aurelia typescript scroll to top of page

如何滚动页面顶部或 div/id 元素?

click.delegate 从视图 (.html) 调用的视图模型 (.ts) 中的方法将页面滚动到顶部或按 id 等选择 div。通过使用 window?如果,如何在aurelia/typescript中注入window?

我没有完全理解你的问题,但是,这是我在每次导航时滚动到页面顶部的方式。也许这对你有帮助。

我有一个滚动函数 (smoothScrollReset),它获取一个元素(可以是每个元素)并根据给定函数滚动到该元素(例如 linearTween(),您可以更改滚动行为通过交换这个)。我滚动到的元素是页面上的某个容器。 然后,我向 Aurelia 路由器添加 post 渲染管道步骤。总计:

添加管道步骤:

...
let appRouterConfig = config => {
  config.addPipelineStep('postRender', ScrollToTopStep);
};

this.router.configure(appRouterConfig);
...

管道步骤本身:

export class ScrollToTopStep {
  run(instruction, next) {
    let element = document.getElementsByTagName('main')[0];
    smoothScrollReset(element);
    return next();
  }
}

滚动功能:

export function smoothScrollReset(element) {
  if (!element) {
    return;
  }

  const duration = 200;
  const scrollFrom = element.scrollTop;
  const diff = -scrollFrom;
  let startTime = null;
  let lastYOffset;
  let scrollLoop = (currentTime) => {
    let currentYOffset = element.scrollTop;
    if (!startTime) {
      startTime = currentTime - 1;
    }

    const timeElapsed = currentTime - startTime;
    if (lastYOffset) {
      if ((diff > 0 && lastYOffset > currentYOffset) ||
        (diff < 0 && lastYOffset < currentYOffset)) {
        return;
      }
    }

    lastYOffset = currentYOffset;
    element.scrollTop = linearTween(timeElapsed, scrollFrom, diff, duration);
    if (timeElapsed < duration) {
      window.requestAnimationFrame(scrollLoop);
    } else {
      element.scrollTop = 0;
    }
  };

  window.requestAnimationFrame(scrollLoop);
}

function linearTween(t, b, c, d) {
  return c * t / d + b;
}