Onclick元素模拟Esc键 [英] Onclick element simulate Esc key

查看:386
本文介绍了Onclick元素模拟Esc键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

当用户单击链接时,应触发通过Javascript Esc键. 因此,为了能够更好地解释它,我有以下内容 到目前为止的代码:

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.我创建了一个函数:

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);
}

还使用jQuery进行了尝试:

also tried this with jQuery:

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

2.当用户单击href时,应调用该函数:

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?

注意:之所以这样问,是因为我激活了带有F11键的弹出窗口(全屏模式).当用户单击关闭按钮时,必须撤消F11,这通常是通过按ESC键来完成的.我希望这可以自动完成.

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.

推荐答案

JavaScript无法从浏览器窗口触发操作系统级别的事件,除非浏览器通过特殊功能或API本地支持它.您不能使用ESC键发送系统级键盘事件以关闭全屏模式,也不能使用F1启动系统帮助.

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.

相反,您可以使用主要浏览器支持的全屏API:

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();
}

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

这篇关于Onclick元素模拟Esc键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆