【发布时间】:2018-09-17 21:30:16
【问题描述】:
假设我有一个包含许多组件的表单。我想检测小组的注意力不集中。因此,应忽略同一表单上从 1 个输入到另一个输入的焦点。我怎样才能做到这一点?
【问题讨论】:
假设我有一个包含许多组件的表单。我想检测小组的注意力不集中。因此,应忽略同一表单上从 1 个输入到另一个输入的焦点。我怎样才能做到这一点?
【问题讨论】:
首先,我们希望能够用一些属性标记组中的每个可聚焦元素,因此当我们切换元素时,我们会知道我们是否在同一个组中。这可以通过数据属性来实现。
groupIdAttribute groupId =
Html.Attributes.attribute "data-group-id" groupId
接下来,我们需要解码onBlur 事件上的事件负载,以查看target 是否与relatedTarget 不同(将获得焦点)。并报告变化。 (注意这里我们通过路径"dataset", "groupId"引用data-group-id)
decodeGroupIdChanged msg =
Json.Decode.oneOf
[ Json.Decode.map2
(\a b ->
if a /= b then
Just a
else
Nothing
)
(Json.Decode.at [ "target", "dataset", "groupId" ] Json.Decode.string)
(Json.Decode.at [ "relatedTarget", "dataset", "groupId" ] Json.Decode.string)
, Json.Decode.at [ "target", "dataset", "groupId" ] Json.Decode.string
|> Json.Decode.andThen (\a -> Json.Decode.succeed (Just a))
]
|> Json.Decode.andThen
(\maybeChanged ->
case maybeChanged of
Just a ->
Json.Decode.succeed (msg a)
Nothing ->
Json.Decode.fail "no change"
)
现在我们可以创建一个onGroupLoss 监听器:
onGroupFocusLoss msg =
Html.Events.on "blur" (decodeGroupIdChanged msg)
然后像这样安装它:
input [onGroupFocusLoss GroupFocusLoss, groupIdAttribute "a"]
这是一个例子(注意它是用 elm-ui 构建的,所以有一些额外的代码。)
【讨论】:
focusout 处理程序,而不是在每个输入上附加blur 处理程序。
focusout 可能会导致代码更简洁。