【发布时间】:2017-11-16 01:05:26
【问题描述】:
我正在使用 purescript-halogen,当子组件的消息被捕获时,我想滚动到 div 的底部。 但是,Halogen 中似乎没有滚动动作控制。 那么,我该如何 Scroll to bottom of div?
我认为一个解决方案是在事件捕获时从 Main 调用其他进程,而不是 Halogen。 我不确定这个解决方案是否不错。
【问题讨论】:
标签: purescript halogen
我正在使用 purescript-halogen,当子组件的消息被捕获时,我想滚动到 div 的底部。 但是,Halogen 中似乎没有滚动动作控制。 那么,我该如何 Scroll to bottom of div?
我认为一个解决方案是在事件捕获时从 Main 调用其他进程,而不是 Halogen。 我不确定这个解决方案是否不错。
【问题讨论】:
标签: purescript halogen
设置滚动位置是通过使用正常的 DOM 功能完成的,目标是渲染的节点。
为此,您需要将 HTML DSL 中的 ref 属性添加到要滚动的节点:
-- Define this in the same module as / in the `where` for a component
containerRef ∷ H.RefLabel
containerRef = H.RefLabel "container"
-- Use it with the `ref` property like so:
render =
HH.div
[ HP.ref containerRef ]
[ someContent ]
然后在组件的eval 中,您可以使用getHTMLElementRef 获取实际创建的DOM 元素,然后更新其上的滚动位置:
eval (ScrollToBottom next) = do
ref ← H.getHTMLElementRef containerRef
for_ ref \el → H.liftEff do
scrollHeight ← DOM.scrollHeight el
offsetHeight ← DOM.offsetHeight el
let maxScroll ← scrollHeight - offsetHeight
DOM.setScrollTop maxScroll el
pure next
这里的 sn-ps 是从一些类似的 real world code 修改而来的,所以应该这样做!
【讨论】:
eval Scroll ref <- H.getHTMLElementRef streamRef for_ ref \el -> H.liftEff do scrollHeight <- scrollHeight $ htmlElementToElement el offsetHeight <- offsetHeight el setScrollTop (scrollHeight - offsetHeight) $ htmlElementToElement et pure next
与https://stackoverflow.com/a/44543329/1685973 的答案基本相同,但我很难找到不同的导入:
import Halogen as H
import Halogen.HTML as HH
import Data.Foldable (for_)
import DOM.HTML.Types (htmlElementToElement)
import DOM.Node.Element (scrollHeight, setScrollTop)
import DOM.HTML.HTMLElement (offsetHeight)
...
-- Define this in the same module as / in the `where` for a component
containerRef ∷ H.RefLabel
containerRef = H.RefLabel "container"
-- Use it with the `ref` property like so:
render =
HH.div
[ HP.ref containerRef ]
[ someContent ]
...
eval (ScrollToBottom next) = do
ref <- H.getHTMLElementRef containerRef
for_ ref $ \el -> H.liftEff $ do
let hel = htmlElementToElement el
sh <- scrollHeight hel
oh <- offsetHeight el
let maxScroll = sh - oh
setScrollTop maxScroll hel
pure next
【讨论】:
htmlElementToElement 只是来自 Web.HTML.HTMLElement 的 toElement。 scroll* 函数现在也在 Web.DOM 中。不过,代码仍然有效。