Onclick element simulate Esc key

本秂侑毒 提交于 2019-12-25 03:37:31

问题


I have the following situation:

When the user clicks on a link, through Javascript Esc key should be triggered. So to be able to explain it better I have the following code so far:

1.I've created a function:

//my function
function invokeEscKey() {
    var ev = document.createEvent('KeyboardEvent');
    ev.initKeyEvent(
        'keydown', true, true, window, false, false, false, false, 27, 0);
    document.body.dispatchEvent(ev);
}

also tried this with jQuery:

//my function
function invokeEscKey() {
    jQuery.event.trigger({
        type : 'keypress', 
        which : 27 
    });
}

2.And when the user clicks on the href, the function should be called:

$(function() {
    $('a.close').click(function() {
        //call this function to simulate ESC key press
        invokeEscKey();
    });
});

But this doesn't work at all. My question is, what is the best way to solve this?

Note: The reason I ask this is because I have a popup with the F11 key (full screen mode) is activated. When the user clicks on the close button, the F11 must be undone, which is normally done by pressing on the ESC key. And I want this to be done automatically.


回答1:


JavaScript can't trigger OS-level events from the browser window, except the cases when it is natively supported by the browser via special functions or APIs. You can't send a system-level keyboard event with ESC key to close fullscreen mode, or, say, launch system help with F1.

Instead you may use Fullscreen API which is supported by major browsers:

if (document.exitFullscreen) {
    document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
    document.webkitCancelFullScreen();
}

MORE: http://www.paulund.co.uk/javascript-full-screen-api



来源:https://stackoverflow.com/questions/28627860/onclick-element-simulate-esc-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!