[英]How do I create an Elm Lang event when scrolling?
I want to know when the user scroll in my webpage.我想知道用户何时在我的网页中滚动。 How do I create an Elm event after each time a user scrolls?
每次用户滚动后如何创建 Elm 事件?
The easiest way is to create an event listener on the div.最简单的方法是在 div 上创建一个事件监听器。 Use the Html.Events on to create a custom event listener.
使用 Html.Events on创建自定义事件侦听器。
That html event then needs to be decoded into an Elm event.然后需要将该 html 事件解码为 Elm 事件。 like this:
像这样:
on "wheel" (Decode.succeed Scroll)
where Scroll
is a Msg
, it can be any of you app's Msg
s.在
Scroll
是Msg
on "wheel" (Decode.succeed Scroll)
上,它可以是任何应用程序的Msg
。 This can be applied to any div.这可以应用于任何 div。 For example here is an implementation with
Elm-UI
to detect a scroll anywhere in the webpage.例如,这里是一个使用
Elm-UI
的实现,用于检测网页中任意位置的滚动。
import Html.Events exposing (on)
import Json.Decode as Decode
view model =
layout
[ htmlAttribute <| on "wheel" (Decode.succeed Scroll)
]
<|
column []
[
~~~ snip
]
You almost certainly want to use a port
to create the scroll event.您几乎肯定想使用
port
来创建滚动事件。 Wheel
cacn have some strange side effects. Wheel
cacn 有一些奇怪的副作用。
It is also recommend to ignore some of the scroll events otherwise your website will generate thousands of events per minute.还建议忽略一些滚动事件,否则您的网站每分钟会产生数千个事件。 This is done with the
ticking
variable below and requestAnimationFrame
.这是通过下面的
ticking
变量和requestAnimationFrame
完成的。 Change ticking > 5
to any int you would like depending on your desired responsiveness.根据您所需的响应能力,将
ticking > 5
更改为您想要的任何 int。
var ticking = 0;
window.addEventListener("scroll", function (event) {
if (ticking > 5) {
window.requestAnimationFrame(function() {
app.ports.recvScroll.send();
ticking = 0;
});
}
ticking += 1;
});
recvScroll
is the name of the port in the related elm code. recvScroll
是相关 elm 代码中的端口名称。 But you can name it whatever you would like.但是你可以随意命名它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.