在Elm中获取页面的scrollTop值 [英] Getting the page scrollTop value in elm

查看:91
本文介绍了在Elm中获取页面的scrollTop值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用Elm语言。我正在制作一个基本的网页,并且要在滚动时将导航栏固定在顶部。

I have started playing around with the language Elm. I am making a basic web page and I would like to make my nav bar stick to the top when scrolling.

我希望能够使我的模型对从页面顶部向下滚动的距离做出反应。

I would like to be able to make my model react to the distance scrolled down from the top of the page.

我有两个问题:


  1. 如何使用Javascript访问此变量?理想情况下,我希望
    类似于JQuery的 $(window).scrollTop(),但没有JQuery

  2. 如何传递此内容值还给榆木?我必须设置端口吗?

  1. How to access this variable with Javascript? Ideally I would like something like JQuery's $(window).scrollTop() but without JQuery
  2. How to pass this value back to Elm? Do I have to set up a port?


推荐答案

您需要设置一个端口Elm中的port用作提供scrollTop距离的信号。由于我们将通过javascript提供该值,因此您只需要声明端口函数签名:

You'll need to set up a port in elm to act as a signal which provides the scrollTop distance. Since we're going to provide that value from javascript, you only need to declare the port function signature:

port scrollTop : Signal Int

单独执行任何操作。您必须编辑javascript,这将启动elm应用程序以提供该信号的值。这是设置该脚本的javascript:

On its own, that will do nothing. You have to edit the javascript which initiates your elm application to provide values for that signal. Here's the javascript to set that up:

<script type="text/javascript">
var app = Elm.fullscreen(Elm.Main, {
  scrollTop: document.body.scrollTop
});

window.onscroll = function () {
  app.ports.scrollTop.send(document.body.scrollTop);
};
</script>

需要注意的两件事:scrollTop信号需要一个初始值。这就是我作为 Elm.fullscreen()的第二个参数发送的内容。这样可以确保在您的应用加载时立即以正确的scrollTop值开始。然后, window.onscroll 处理程序会在每次滚动窗口时向该信号发送新的scrollTop值。

Two things to note: You need an initial value for the scrollTop signal. That's what I'm sending in as the second parameter to Elm.fullscreen(). This guarantees that, when your app loads, it will start off with the correct scrollTop value right away. The window.onscroll handler then sends new scrollTop values to that signal any time the window is scrolled.

要测试这样,我们可以编写一个简单的调试端口,该端口将更改浏览器标题栏以显示当前的scrollTop值。将此添加到elm文件:

To test this out, we can write a simple little debugging port that will change the browser title bar to show the current scrollTop value. Add this to the elm file:

port title : Signal String
port title =
  Signal.map toString scrollTop

最后,对于我们的测试,我们只需要一个高页。这应该可以解决问题:

Lastly, for our test, we just need a tall page. This should do the trick:

main =
  let
    line n =
      div [] [ text <| "Line #" ++ (toString n) ]
  in
    div []
      <| List.map line [0..100]

我在此处提供了完整代码: Main.elm 滚动测试。 html 。您可以在本地进行编译,然后在页面上上下滚动时观察标题栏的变化。

I have the provided the full code here: Main.elm and scroll-test.html. You can compile that locally, then watch the title bar change as you scroll up and down on the page.

这篇关于在Elm中获取页面的scrollTop值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆