Detect whether browser has keyboard/arrow keys in web page

前端 未结 8 892
忘了有多久
忘了有多久 2020-12-31 00:21

I have a full-screen game in HTML+JavaScript, which uses the arrow keys as primary controls. This cannot be used on keyboardless Android devices (I haven\'t tested on iOS),

相关标签:
8条回答
  • 2020-12-31 00:56

    Use feature detection with Modernizr: http://www.modernizr.com/docs/#touch

    While this is not a reliable way to check if the user has a keyboard it is definitely reliable to see if the browser is capable of touch.

    0 讨论(0)
  • 2020-12-31 00:58

    An alternate way would be to bind swipe events & keycodes to the same functions - so both would work at the same time (sure that depends if the game shall accept swipes - or has some joypad controls on screen).

    This even covers the dis-advance mentioned in the answer's comments, I've just noticed.

    In most cases on-screen tap-controls are too difficult to use (S-NES Emu).

    The best ones I've used so far were the ones in Bard's Tale for Droid.

    Tip: best for controlling directional movement in a game would be the tap-hold event. So one can tap-hold ... needs some invisible construction line between the cursor and the center of the screen - in order to measure the degrees for the vector of movement.

    One could probably even control the speed by the value of the pressure - just currently not sure if the property can be accessed from within JavaScript - or if this only available in Android SDK?

    In Parallel Kingdom one moves by single-tap (but the character isn't always in the middle of the screen, like it would be with the tap-hold method mentioned above).

    0 讨论(0)
  • 2020-12-31 01:08

    look for touch specific events such as touchstart or gesturestart and show the onscreen controls if detected.

    http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html

    I am not sure if the system-info api has been implemented by any browsers: http://www.w3.org/TR/system-info-api/

    0 讨论(0)
  • 2020-12-31 01:10

    You could use javascript to find out the height of the windows view port and then us an if statement saying:

    if ($(window).height() <= "960")) {
        //Your code to display keyboard controls
        //P.S. 960 is height of iPhone 4+ screen
    }
    

    Edit: Left out ) at end of $(window).height() <= "960"

    0 讨论(0)
  • 2020-12-31 01:11

    Instead of trying to guess, make it a config option for the user to choose.

    0 讨论(0)
  • 2020-12-31 01:15

    No need for any user-agent sniffing, config options or any kind of guessing. Just do this:

    1. Have a title screen which says "press to continue".
    2. On click or key press, hide touch controls and start game.
    3. On touch, show touch controls and start game.

    You never even needed to mention the option to the user and you auto-detected their preferred control perfectly.

    0 讨论(0)
提交回复
热议问题