1. 程式人生 > >jQuery 事件 - keydown() 方法的應用

jQuery 事件 - keydown() 方法的應用

jQuery 事件 - keydown() 方法的應用

實現一個需求:當按住鍵盤的上下左右鍵的時候,自定義一個小球會向你控制的方向移動。
原理:當發生 keydown 事件時執行一個函式,結合上下左右四個鍵位的ASCII 碼實現不同的效果。
效果展示:在這裡插入圖片描述

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>測試</title>
</head>
<style>
    .div1{
        width: 100px;
        height:100px;
        position: absolute;
        left:50%;
        margin-left:-50px;
        background: #af1819;
        border-radius: 50%;
    }
</style>
<body>
<div class="div1"></div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script>
    $(document).keydown(function(e){
        if(e.keyCode==40)  //向下移動
        {
            $(".div1").css("top",parseInt($('.div1').css('top'))+10+'px') //parseInt()字串轉換成數字
        };
        if(e.keyCode==38)
        {
            console.log(parseInt($('.div1').css('top')) -10 +'px');

            $(".div1").css("top",parseInt($('.div1').css('top')) -10 +'px')
        };
        if(e.keyCode==37)
        {
            // console.log(e.keyCode)
            $(".div1").css("left",parseInt($('.div1').css('left'))-10+'px')
        };
        if(e.keyCode==39)
        {
            // console.log(e.keyCode)
            $(".div1").css("left",parseInt($('.div1').css('left'))+10+'px')
        };

    })
</script>
</html>