【问题标题】:Why won't my code to detect ctrl key state work?为什么我的代码无法检测 ctrl 键状态?
【发布时间】:2012-04-10 01:05:07
【问题描述】:

如果用户点击 enter 时按下 shift,我会尝试打开新窗口,如果用户点击 ctrl,我会尝试打开新标签. shift 部分有效,但 ctrl 部分无效...

var ctrlPressed = false;
var shiftPressed = false;
var stb = null;
function onload() {
stb = document.getElementById("searchTextBox");
}
    function enter(e) {

        if (e.keyCode == 13) {
            if (!ctrlPressed && !shiftPressed) {
            window.location = "http://search.yahoo.com/search?p=" + encodeURI(stb.value) + "&fr2=sb-top&fr=404_web&pqstr=" + encodeURI(stb.value);
            }
            else if (ctrlPressed) {
            window.open("http://search.yahoo.com/search?p=" + encodeURI(stb.value) + "&fr2=sb-top&fr=404_web&pqstr=" + encodeURI(stb.value));
            }
            else if (shiftPressed) {
            window.open("http://search.yahoo.com/search?p=" + encodeURI(stb.value) + "&fr2=sb-top&fr=404_web&pqstr=" + encodeURI(stb.value), "_blank");
            }
        }
    }
    function searchdown(e) {
        if (e.keyCode == 17) {
            ctrlPressed = true;
        }
        else if (e.keyCode == 16) {
            shiftPressed = true;
        }
    }
    function searchup(e) {
        if (e.keyCode == 17) {
            ctrlPressed = false;
        }
        else if (e.keyCode == 16) {
            shiftPressed = false;
        }
    }

我也不能使用 jQuery...

【问题讨论】:

  • 您的活动委托在哪里?

标签: javascript html dom-events internet-explorer-9 keypress


【解决方案1】:

您知道event.ctrlKey 会告诉您是否按住控制键吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2014-12-14
    • 1970-01-01
    相关资源
    最近更新 更多