【问题标题】:Scroll action in PureScript HalogenPureScript Halogen 中的滚动操作
【发布时间】:2017-11-16 01:05:26
【问题描述】:

我正在使用 purescript-halogen,当子组件的消息被捕获时,我想滚动到 div 的底部。 但是,Halogen 中似乎没有滚动动作控制。 那么,我该如何 Scroll to bottom of div?

我认为一个解决方案是在事件捕获时从 Main 调用其他进程,而不是 Halogen。 我不确定这个解决方案是否不错。

【问题讨论】:

    标签: purescript halogen


    【解决方案1】:

    设置滚动位置是通过使用正常的 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
    【解决方案2】:

    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
    

    【讨论】:

    • API 发生了一些变化 - 现在 htmlElementToElement 只是来自 Web.HTML.HTMLElementtoElementscroll* 函数现在也在 Web.DOM 中。不过,代码仍然有效。
    猜你喜欢
    • 2016-03-17
    • 2019-10-02
    • 1970-01-01
    • 2015-11-21
    • 2017-06-02
    • 2023-04-02
    • 2016-02-04
    • 2017-03-06
    • 1970-01-01
    相关资源
    最近更新 更多