JavaScript外设——键盘事件


0.前言

上一节讲了鼠标事件,现在来说说他的“兄弟”——键盘事件。

1.键盘事件

  • keydown:按下任意按键触发(持续调用);
  • keyup:抬起任意按键触发;
  • keypress:按下非(ctrl,alt,shift,capsLock,NumLock)(持续调用)
    注意:键盘事件是给document设置的。



    
    键盘事件与键盘事件的event对象


    


效果:

JavaScript外设——键盘事件_第1张图片
捕获.PNG

altKey是键盘 Alt键;
ctrKey是键盘 Ctrl键;
keyCode表示的是你所按下的键盘的ASCII码;
shiftKey是键盘 Shift键。
我们来测试一下:

document.onkeyup = function(e) {
            var evt = e || window.event;

            console.log(evt);
            console.log(evt.altKey, evt.ctrlKey, evt.shiftKey, evt.keyCode);
        };

document.onkeypress = function(e) {
            var evt = e || window.event;

            console.log(evt);
            console.log(evt.altKey, evt.ctrlKey, evt.shiftKey, evt.keyCode);
        };

效果自行演示,就不一一说明了。

扩展:获取屏幕的宽度和高度

//获取宽度
function $w() {
    return document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
}

//获取高度
function $h() {
    return document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight;
}

这有一个小例子:
html文件




    
    键盘事件应用小例子


    

sunckBase.js代码如下:

//随机颜色
function randomColor() {
    var r = parseInt(Math.random() * 256);
    var g = parseInt(Math.random() * 256);
    var b = parseInt(Math.random() * 256);

    var colorString = "rgb(" + r + "," + g + "," + b + ")";
    return colorString;
}
//获取内部外部样式表中的样式属性的属性值
// obj--- 元素节点
// name----属性名
function getStyle(obj, name){
    if (obj.currentStyle) {
        return obj.currentStyle[name];
    }else{
        return window.getComputedStyle(obj,null)[name];
    }
}

//设置元素样式属性
//obj--元素节点
//name--样式属性名
//value--样式属性值
function setStyle(obj, name, value) {
    obj.style[name] = value;
}


//获取宽度
function $w() {
    return document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
}

//获取高度
function $h() {
    return document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight;
}

2.总结

  节就这么简单,想必对大家都能够有所帮助,谢谢能够的大家的支持!!!!

你可能感兴趣的:(JavaScript外设——键盘事件)