js小功能-滑块移动 和 俄罗斯方块式 键盘操作移动

滑块移动

<script type="text/javascript">
    var div = document.createElement('div');

    document.body.appendChild(div);
    div.style.width = "50px";
    div.style.height = "50px";
    div.style.backgroundColor = "red";
    div.style.position = "absolute";
    div.style.left = "0";
    div.style.top = "0";
    var speed = 1;
    setInterval(function(){
        speed += speed/20;
        div.style.left = parseInt(div.style.left) + speed + "px";
        div.style.top = parseInt(div.style.top) + speed + "px";
    },30);
</script>

这里写图片描述

俄罗斯方块式 键盘操作移动

<script type="text/javascript">
    var div = document.createElement('div');

    document.body.appendChild(div);
    div.style.width = "50px";
    div.style.height = "50px";
    div.style.backgroundColor = "red";
    div.style.position = "absolute";
    div.style.left = "0";
    div.style.top = "0";
    var speed = 1;
    document.onkeydown = function(e){//键盘敲击事件
        //console.log(e);//点击键盘上的上下左右来控制移动
        //顺时针:left:37;top:38;right:39;bottom:40;
        switch (e.which){
            case 37://left
                div.style.left=parseInt(div.style.left) - speed + "px";
                break;
            case 38://top
                div.style.top=parseInt(div.style.top) - speed + "px";
                break;
            case 39://right
                div.style.left=parseInt(div.style.left) + speed + "px";
                break;
            case 40://bottom
                div.style.top=parseInt(div.style.top) + speed + "px";
                break;
        }
    }
</script>

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_39396275/article/details/81782071