你想要document.hasFocus()
。雖然它不會觸發事件,但您必須爲此進行輪詢。
下面是一個例子(run):
port module Main exposing (..)
import Html as H exposing (Html)
import Time
port focusStateRequest :() -> Cmd msg
port focusStateResponse : (Bool -> msg) -> Sub msg
type alias Model =
{ windowFocused : Bool }
type Msg
= FocusStateRequest
| FocusStateResponse Bool
main : Program Never Model Msg
main =
H.program
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
init : (Model, Cmd Msg)
init =
({ windowFocused = True }
, Cmd.none
)
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
FocusStateRequest ->
(model
, focusStateRequest()
)
FocusStateResponse isFocused ->
-- reset your ctrlPressed here if False
({ model | windowFocused = isFocused }
, Cmd.none
)
view : Model -> Html Msg
view model =
model
|> toString
|> H.text
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ Time.every (500 * Time.millisecond) (\_ -> FocusStateRequest)
, focusStateResponse FocusStateResponse
]
而且對JS的一面:
var app = Elm.Main.fullscreen();
app.ports.focusStateRequest.subscribe(function() {
var hasFocus = document.hasFocus();
app.ports.focusStateResponse.send(hasFocus);
});