JS 键盘事件、防止页面元素被复制

键盘事件

<input type="text" id="username" value="iloveyou">
<script type="text/javascript">
    //获取元素
    var username = document.getElementById('username');
    // on 当...时候  key按键  down向下的
    username.onkeydown = function() {
        console.log('键盘被按下了哦!!!!down');
    }

    //press 按压
    username.onkeypress = function() {
        console.log('键盘按下了  press')
    }

    //up 
    username.onkeyup = function() {
        console.log('键盘抬起来了!!! up');
    }

    //获取input元素的值
    var value = username.value;
    username.value = 'imissyou';
</script>

e.g. 将input元素中的值变成大写

<input type="text" id = "user">
<script type="text/javascript">
var user = document.getElementById('user');

user.onkeyup = function() {
    //获取当前input元素的值
    var v = this.value.toUpperCase();
    //修改元素的值
    this.value = v;
}
</script>

e.g. 组合键

window.onkeydown =function(e) {
    //获取keyCode属性
    var key = e.keyCode;
    if(key == 49 && e.ctrlKey == true){
        alert('正在加血!!!!');
    }

    if(key == 50 && e.shiftKey == true){
        alert('正在加蓝!!!');
    }

    if(key == 51 && e.altKey == true) {
        alert('正在放大招!!!');
    }

    return false;
}

键盘移动div

* {
    margin:0px;
    padding:0px;
}
#move {
    position:absolute;
}
<div id="move" style="width:200px;height:200px;background:#456987"></div>
<script type="text/javascript">
var move = document.getElementById('move');

window.onkeydown = function(e) {
    // console.log(e);
    var key = e.keyCode;
    switch(key) {
        case 37:
            moveLeft();
            break;
        case 38:
            moveUp();
            break;
        case 39:
            moveRight();
            break;
        case 40:
            moveDown();
            break;
    }
}

function moveRight() {
    //获取当前元素距离左侧的偏移量
    var l = move.offsetLeft;
    //
    var newLeft = l + 5;
    //设置
    move.style.left = newLeft + 'px';
}


function moveLeft() {
    //获取当前元素距离左侧的偏移量
    var l = move.offsetLeft;
    //
    var newLeft = l - 5;
    //设置
    move.style.left = newLeft + 'px';
}

function moveUp() {
    var t = move.offsetTop;
    var newTop = t - 5;
    move.style.top = newTop + 'px';
}

function moveDown() {
    var t = move.offsetTop;
    var newTop = t + 5;
    move.style.top = newTop + 'px';
}
</script>

防止页面元素被复制

<p>在计算机中,所有的数据在存储和运算时都要使用二进制数...拉丁文字字母。</p>
<script type="text/javascript">
    // 阻止右键
    window.oncontextmenu = function(){
        return false;
    }

    //键盘按下事件
    window.onkeydown = function(e) {
        // console.log(e);
        if(e.ctrlKey == true && e.keyCode == 67) {
            return false;
        }
    }
</script>