为什么我的代码检测到ctrl键状态不起作用?

时间:2012-04-10 01:05:07

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

如果在用户单击输入时按 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;
        }
    }

[edit]我也不能使用jquery

1 个答案:

答案 0 :(得分:2)

您是否知道event.ctrlKey告诉您控制键是否被按下?