榆木-如何在外部单击时关闭模式窗口

时间:2018-06-30 10:42:51

标签: javascript elm

这是代码:

modalWindow :
  Lang -> String ->
  Action -> Action ->
  List (Html Action) -> Html Action
modalWindow lang heading accept close inputs =
  let
    cancel = case lang of
      Es -> "Cancelar"
      En -> "Cancel"
    buttons =
      H.div [A.class "flex-center-div"]
        [ H.input
            [ A.class "textarea-editor-modal-button"
            , A.type_ "button"
            , A.value "OK"
            , E.onClick accept
            ] []
        , H.input
            [ A.class "textarea-editor-modal-button"
            , A.type_ "button"
            , A.value cancel
            , E.onClick close
            ] []
        ]
  in
    H.div [A.class "textarea-editor-modal-window", E.onClick close]
      [ H.div [A.class "textarea-editor-modal-content"] <|
          [ H.div [A.class "textarea-editor-modal-title"] [H.text heading] ]
          ++ inputs ++ [buttons]
      ]

问题出在in之后的行中,因为即使我单击它的内部,它也会关闭模式。

根据https://www.w3schools.com/howto/howto_css_modals.asp,我应该使用event.target来区分内部内部或外部的点击。

2 个答案:

答案 0 :(得分:2)

您的建议可行,或者您可以使用始终成功的解码器和preventDefault = True向第一个div中添加onMouseDown事件处理程序。唯一的问题是您需要添加一条NoOp消息

mouseDownPreventDefault : msg -> Attribute msg
mouseDownPreventDefault noop =
    onWithOptions "mousedown"
        { stopPropagation = False
        , preventDefault = True
        }
        (Json.Decode.succeed noop)

答案 1 :(得分:1)

modalWindow :
  Lang -> String ->
  Action -> Action ->
  List (Html Action) -> Html Action
modalWindow lang heading accept close inputs =
  let
    cancel = case lang of
      Es -> "Cancelar"
      En -> "Cancel"
    buttons =
      H.div [A.class "flex-center-div"]
        [ H.input
            [ A.class "textarea-editor-modal-button"
            , A.type_ "button"
            , A.value "OK"
            , E.onClick accept
            ] []
        , H.input
            [ A.class "textarea-editor-modal-button"
            , A.type_ "button"
            , A.value cancel
            , E.onClick close
            ] []
        ]
  in
    H.div
      [ A.class "textarea-editor-modal-window"
      , E.onClick close
      ]
      [ H.div
          [ A.class "textarea-editor-modal-content"
          , E.onWithOptions
              "click"
              {stopPropagation = True, preventDefault = False}
              (succeed NoOp)
          ]
          <|
          [ H.div [A.class "textarea-editor-modal-title"] [H.text heading]
          ] ++ inputs ++ [buttons]
      ]

我关注了(@Simon H)评论,它有效! (如果我也在包装器上也使用"mousedown",则仅与E.onMouseDown一起使用,但是如果我在两个地方都使用click,也可以使用)