JavaScript09-DOM操作事件02

JavaScript09-DOM操作事件02

1.鼠标事件

window.onload = function () {
    // 鼠标右键的点击事件。
    // 点击鼠标右键弹出菜单,是contextmenu事件的默认行为。
    // 可以通过取消默认行为来禁止,contextmenu的默认行为。
    document.addEventListener('contextmenu', function (event) {
        event.preventDefault();
        console.log('鼠标右键被点击了');
    });

    // wheel 鼠标的滚轮事件。
    document.addEventListener('wheel', function (event) {
        // deltaY 获取滚轮垂直滚动的距离。
        let y = event.deltaY;
        console.log(y);
        if (y > 0) {
            console.log('向下滚动');
        } else {
            console.log('向上滚动');
        }

        // deltaX 获取滚轮水平滚动的距离。
        let x = event.deltaX;
        console.log(x);
    })
}

2.键盘事件

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>04-键盘事件</title>
    <script>
        window.onload = function () {
            // 1 键盘事件,
            //      keydown 按键按下事件,任意键按下后都会触发。
            //      keyup 按键松开事件,在按键按下后的松开时触发。
            //      keypress 按键按下事件,CAPSLOCK、SHIFT、ALT、CTRL按下后不会触发。

            // 2 键盘事件只能绑定给可以获取焦点的元素或者document。
            //      可以获取焦点的元素,input、a、文本框、选择框等。

            // 3 如果按着某个键不松开,按键按下事件会被连续触发。
            //      但是第一次触发和第二次触发之间的间隔会比较长,这么设计为了防止用户误操作。

            // div是不可以获取到焦点的元素,所以绑定了键盘事件也无响应。
            document.getElementById('div01').addEventListener('keydown', function () {
                console.log('123');
            });

            // input可以获取到焦点。
            document.getElementById('input01').addEventListener('keydown', function () {
                console.log('123');
            });

            // a标签可以获取到焦点。
            document.getElementById('a01').addEventListener('keydown', function () {
                console.log('123');
            });

            // 给document绑定keydown事件。
            document.addEventListener('keydown', function () {
                console.log('123456');
            });

            // 给input绑定键盘按下事件。
            document.getElementById('input02').addEventListener('keydown', function (event) {
                // 防止input的按下事件传播给document。
                event.stopPropagation();
                // 获取按下的键,对于方向键上下左右,返回ArrowUp、ArrowDown、ArrowLeft、ArrowRight。
                console.log(event.key);
            });
            
            document.getElementById('input03').addEventListener('keydown', function (event) {
                event.stopPropagation();

                // 获取按下的是a键。
                // 如果没有锁定大写,则返回a。如果锁定了大小写,则返回A。
                // 所以需要使用event.key.toLowerCase(),来判断按下的是a键。
                if (event.key === 'a') {
                    console.log('按下a');
                }

                if (event.key === 'A') {
                    console.log('按下A');
                }
            });


            document.getElementById('input04').addEventListener('keydown', function (event) {
                event.stopPropagation();

                // 同时按下Ctrl和a键。
                if (event.key === 'a' && event.ctrlKey) {
                    console.log('ctrl + a');
                }
            });

            // 给input绑定键盘松开事件,松开事件只有在键盘按下后才会触发。
            document.getElementById('input05').addEventListener('keypress', function (event) {
                event.stopPropagation();

                console.log(event.key);
            });
        }
    </script>
</head>
<body>

<div id="div01"></div>

<input type="text" id="input01">

<a href="javascript:;" id="a01">超链接</a>

<input type="text" id="input02">
<input type="text" id="input03">
<input type="text" id="input04">
<input type="text" id="input05">
</body>
</html>

3.键盘事件练习-通过方向键移动div

<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        #div01 {
            width: 100px;
            height: 100px;
            background-color: orange;
            position: absolute;
        }
    </style>

    <script>
        window.onload = function () {
            let div01 = document.getElementById('div01');
            document.addEventListener('keydown', function (event) {
                if (event.key === 'ArrowUp' || event.key === 'Up') {
                    // offsetTop,当前元素相当于offsetParent的上偏移量。
                    div01.style.top = div01.offsetTop - 10 + 'px';
                }

                if (event.key === 'ArrowDown' || event.key === 'Down') {
                    div01.style.top = div01.offsetTop + 10 + 'px';
                }

                if (event.key === 'ArrowLeft' || event.key === 'Left') {
                    div01.style.left = div01.offsetLeft - 10 + 'px';
                }

                if (event.key === 'ArrowRight' || event.key === 'Right') {
                    div01.style.left = div01.offsetLeft + 10 + 'px';
                }
            })
        }
    </script>
</head>
<body>

<div id="div01"></div>
</body>
</html>

4.定时调用

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>06-定时调用</title>
    <script>
        // setTimeout() 延时调用,在指定时间后调用,并且只会调用一次。
        //      参数一,延时调用的函数;参数二,延时的时间。
        // clearTimeout() 可以通过setTimeout()返回的以为id来闭关setTimeout()。
        window.onload = function () {
            document.getElementById('button01').onclick = function () {
                let timer = setTimeout(function () {
                    document.getElementById('div01').innerHTML = 1;
                }, 1000);

                // 关闭延时调用。
                clearTimeout(timer);
            };

            // setInterval() 定时调用。
            // 参数一,定时调用的函数;参数二,定时的时间。

            // clearInterval() 可以通过setInterval()返回的以为id来闭关setInterval()。
            let num = 0;
            document.getElementById('button02').onclick = function () {
                let timer = setInterval(function () {
                    document.getElementById('div02').innerHTML = num++;
                }, 1000);

                // 关闭定时调用。
                clearInterval(timer);
            };


            // 通过setTimeout()实现定时调用。
            document.getElementById('button03').onclick = function () {
                setTimeout(function test() {
                    document.getElementById('div03').innerText = num++;
                    
                    setTimeout(test, 1000);
                }, 1000);
            }
        }
    </script>
</head>
<body>

<button id="button01">button01</button>
<button id="button02">button02</button>
<button id="button03">button03</button>

<div id="div01"></div>
<div id="div02"></div>
<div id="div03"></div>
</body>
</html>

5.键盘事件练习-通过方向键移动div,通过定时调用解决连续输入后第一次的卡顿问题

<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        #div01 {
            width: 100px;
            height: 100px;
            background-color: orange;
            position: absolute;
        }
    </style>

    <script>
        // 如果按下某个键不松开,按键按下事件会被连续触发。
        // 但是第一次触发和第二次触发之间的间隔会比较长,这么设计为了防止用户的误操作。
        // 可以使用定时调用来解决第一次触发和第二次触发之间的间隔会比较长的问题。
        window.onload = function () {
            // 上下左右方向键
            let direction = null;
            let div01 = document.getElementById('div01');

            setInterval(function () {
                if (direction === 'ArrowUp' || direction === 'Up') {
                    div01.style.top = div01.offsetTop - 10 + 'px';
                }

                if (direction === 'ArrowDown' || direction === 'Down') {
                    div01.style.top = div01.offsetTop + 10 + 'px';
                }

                if (direction === 'ArrowLeft' || direction === 'Left') {
                    div01.style.left = div01.offsetLeft - 10 + 'px';
                }

                if (direction === 'ArrowRight' || direction === 'Right') {
                    div01.style.left = div01.offsetLeft + 10 + 'px';
                }
            }, 30);
			
            // 按下后修改方向键
            document.addEventListener('keydown', function (event) {
                direction = event.key;
            });

            // 松开收将方向键设置为null。
            document.addEventListener('keyup', function () {
                direction = null;
            });
        }
    </script>
</head>
<body>

<div id="div01"></div>
</body>
</html>

6.DOM操作联系-贪吃蛇

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>08-贪吃蛇</title>
    <style>
        /*清除默认样式*/
        * {
            margin: 0;
            padding: 0;
        }

        /*设置主容器样式*/
        #main {
            width: 340px;
            height: 400px;
            /*设置边框*/
            border: 10px solid black;
            /*设计圆角*/
            border-radius: 10%;
            /*设置居中*/
            margin: 100px auto;
            background-color: #b7d4a8;
            /*设置弹性容器*/
            display: flex;
            /*设置弹性盒的主轴方向,垂直排列*/
            flex-flow: column;
            /*设置侧洲的对齐方式,水平对齐*/
            align-items: center;
            /*设置主轴的对齐方式*/
            justify-content: space-around;
        }

        /*设置游戏区域的样式*/
        #gameRegion {
            width: 300px;
            height: 300px;
            border: 2px solid black;
            /*开启相对定位,方便设置蛇和食物的位置*/
            position: relative;
        }

        /*设置蛇的样式*/
        #snake > div {
            /*设置盒子大小的计算方式*/
            box-sizing: border-box;
            width: 10px;
            height: 10px;
            background-color: black;
            /*蛇需要移动,所以开启绝对定位*/
            position: absolute;
            /*设置蛇的边框*/
            border: 1px solid #b7d4a8;
            /*设置圆角*/
            border-radius: 4px;
        }

        /*设置食物的样式*/
        #food {
            box-sizing: border-box;
            width: 10px;
            height: 10px;
            /*食物需要移动,所以开启绝对定位*/
            position: absolute;
            left: 100px;
            top: 100px;
        }

        #food > div {
            width: 50%;
            height: 50%;
            background-color: black;
            float: left;
            /*旋转45*/
            transform: rotate(45deg);
            border-radius: 2px;
        }

        /*设置分数区域的样式*/
        #scoreRegion {
            width: 304px;
            /*设置字体*/
            font: bold 20px 'Courier';
            /*设置弹性盒*/
            display: flex;
            /*设置主轴的对齐方式*/
            justify-content: space-between;
        }
    </style>

    <script>
        window.onload = function () {
            // 食物
            let food = document.getElementById('food');
            // 保存蛇的容器
            let snakeContainer = document.getElementById('snake');
            // 蛇
            let snake = snakeContainer.getElementsByTagName('div');
            // 分数
            let score = document.getElementById('score');
            let level = document.getElementById('level');
            let s = 0, l = 1;

            // 蛇移动的方向
            let direction;

            // 随机生成一个食物的位置,并修改食物的位置
            function makeFood() {
                // 食物的坐标范围 0-290
                let left = Math.round(Math.random() * 29) * 10;
                let top = Math.round(Math.random() * 29) * 10;

                food.style.left = left + 'px';
                food.style.top = top + 'px';
            }

            // 监听键盘上下左右键的输入,来改变蛇的位置。
            document.addEventListener('keydown', function (event) {
                // 保存方向键,避免蛇移动时,按下其他键导致蛇停止移动。
                let keyArr = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Up', 'Down', 'Left', 'Right'];
                if (keyArr.indexOf(event.key) !== -1) {
                    direction = event.key;
                }
            });

            // 通过定时任务移动蛇的位置
            setTimeout(function main() {
                // 蛇当前的位置
                let left = snake[0].offsetLeft;
                let top = snake[0].offsetTop;


                switch (direction) {
                    case 'ArrowUp':
                    case 'Up':
                        // 向上
                        top -= 10;
                        // 禁止蛇掉头
                        if (snake[1] && snake[1].offsetTop === top) {
                            top += 20;
                        }
                        break;
                    case 'ArrowDown':
                    case 'Down':
                        // 向下
                        top += 10;
                        if (snake[1] && snake[1].offsetTop === top) {
                            top -= 20;
                        }
                        break;
                    case 'ArrowLeft':
                    case 'Left':
                        // 向左
                        left -= 10;
                        if (snake[1] && snake[1].offsetLeft === left) {
                            left += 20;
                        }
                        break;
                    case 'ArrowRight':
                    case 'Right':
                        // 向左
                        left += 10;
                        if (snake[1] && snake[1].offsetLeft === left) {
                            left -= 20;
                        }
                        break;
                }

                // 蛇撞到墙检测
                if (top > 290 || top < 0 || left > 290 || left < 0) {
                    alert('游戏结束');
                    return;
                }

                // 判断蛇是否吃到食物
                if (top === food.offsetTop && left === food.offsetLeft) {
                    // 修改食物的位置
                    makeFood();
                    let newSnakeBody = document.createElement('div');
                    // 1 将蛇的新的身体追加到最后。
                    snakeContainer.appendChild(newSnakeBody);

                    // 2 将新的蛇的身体作为蛇头
                    //snakeContainer.insertAdjacentElement('afterbegin', newSnakeBody);
                    s++;
                    score.innerHTML = s;
                    if (s % 10 === 0) {
                        l++;
                        level.innerHTML = l;
                    }
                }

                // 蛇的身体移动
                for (let i = snake.length - 1;i > 0;i--) {
                    let bodyTop = snake[i - 1].offsetTop;
                    let bodyLeft = snake[i - 1].offsetLeft;

                    // 如果蛇头的位置和身体的位置相同游戏结束
                    if (bodyTop === top && bodyLeft === left) {
                        alert('游戏结束');
                        return;
                    }

                    snake[i].style.top = bodyTop + 'px';
                    snake[i].style.left = bodyLeft + 'px';
                }

                // 通过改变蛇当前的方向来移动蛇的位置。
                snake[0].style.top = top + 'px';
                snake[0].style.left = left + 'px';

                // 根据等级设置蛇移动的快慢
                setTimeout(main, 300 - (20 * (l - 1)));
            }, 300);
        }
    </script>
</head>
<body>

<!-- 定义游戏的容器 -->
<div id="main">
    <!-- 定义游戏区域 -->
    <div id="gameRegion">

        <!-- 创建蛇 -->
        <div id="snake">
            <!-- 蛇头 -->
            <div id="snakeHead"></div>
        </div>

        <!-- 创建食物 -->
        <div id="food">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>

    <!-- 定义分数区域 -->
    <div id="scoreRegion">
        <!-- 创建分数容器 -->
        <div>
            SCORE:<span id="score">0</span>
        </div>

        <!-- 创建等级容器 -->
        <div>
            LEVEL:<span id="level">1</span>
        </div>
    </div>
</div>
</body>
</html>
posted @ 2022-08-27 11:55  行稳致远方  阅读(37)  评论(0)    收藏  举报