首先,我们希望能够用一些属性标记组中每个可聚焦的元素,这样当我们切换元素时,我们就知道我们是否在同一个组中。这可以通过数据属性来实现。
groupIdAttribute groupId =
Html.Attributes.attribute "data-group-id" groupId
接下来,我们需要解码
onBlur
事件以查看
target
relatedTarget
(这将获得焦点)。并报告变化(注意这里我们指的是
data-group-id
通过小路
"dataset", "groupId"
)
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构建的,因此有一些额外的代码)
https://ellie-app.com/3nkBCXJqjQTa1