javascript - 按键打开未聚焦的选项卡

标签 javascript jquery internet-explorer-8 jquery-selectors jquery-events

我有以下代码,可以正常工作:

// click on the button
$(".btnHeaderSearch").click(function(event) 
{ 
    event.preventDefault();
    window.open('/search.aspx?phrase=' + $('.txtHeaderSearch').val());
});

它将在新窗口/选项卡中打开 search.aspx,并且该窗口/选项卡将具有焦点或位于所有其他窗口/选项卡的前面。

但是,以下代码不起作用:

// press enter key when textbox has focus to simulate button click:
$('.txtHeaderSearch').bind('keyup', function(e) {
    if ( e.keyCode === 13 ) { // 13 is enter key
        window.open('/search.aspx?phrase=' + $('.txtHeaderSearch').val());
    }
});

这里发生的情况是窗口/选项卡确实打开了,但它在所有其他窗口后面打开了一个窗口,或者它打开了一个选项卡而不给予选项卡焦点,所以我最终留在了原始页面上。

如何按下回车键来打开一个窗口/选项卡,其行为与上面单击按钮的方式相同?即,我希望这两个代码都可以打开一个立即获得焦点的窗口或选项卡,就像当前的单击一样。

我在 IE8 中遇到了这种行为。它在 Google Chrome 中运行良好,我还没有在任何其他浏览器上尝试过。不幸的是,我需要让它在 IE8 中工作。

最佳答案

来自http://msdn.microsoft.com/en-us/library/ie/ms537632(v=vs.85).aspx :

Ensure that all of the pop-up windows in your Web site open as the direct result of a user action, such as clicking a page element, or tabbing to a link and then pressing ENTER.

事实上,你的代码根本不适合我,IE 默认弹出窗口阻止程序只是阻止了它。我认为这是 Not Acceptable ,因为大多数用户不允许。

我通过在按下回车键时将焦点移动到隐藏链接(与按 Tab 键相同)来解决这个问题(很重要,因为在按键后为时已晚),并且当释放它时,它将与按回车键相同在该链接上时,弹出窗口将打开。

HTML:

<input class="txtHeaderSearch">
<a id="hidden-link" href="#">needs to have content</a>

CSS:

#hidden-link {
    position: absolute;
    left: -9999px;
    top: -9999px;
}

Javascript:

$('.txtHeaderSearch').bind('keydown', function(e) {
    if (e.which === 13) { // which is normalized by jQuery
        $("#hidden-link").focus();
    }
});

$("#hidden-link").click(function() {
    var win = window.open('/search.aspx?phrase=' + $('.txtHeaderSearch').val());
    //win.focus(); 
    //The above is optional, if the window opens but doesn't focus then uncomment the above line
});

演示:

http://jsfiddle.net/UCcqM/2/

同样的解决方法不适用于其他浏览器,因此您需要检测 IE 并根据浏览器有条件地使用适当的解决方案。

关于javascript - 按键打开未聚焦的选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11690128/

相关文章:

javascript - 使用嵌入或 iframe 在模态中使用 Angular 4 上传前预览

javascript - 在 Angular 中使用 `fetch`

php - Jquery Submit() 基于php脚本返回值的html表单

javascript - 追加<th>的innerhtml

php - 提交后出现错误结果 IE8 的错误 css

javascript - 在 Wordpress 中使用 Avada 主题将 HTML 和 JavaScript 添加到页面

javascript - 打乱图像 - Javascript

javascript - jquery返回不存在的id或类的值?

html - IE8 表格未正确调整大小 <td>

html - 像 twitter bootstrap 一样的单杠图标