为什么把鼠标事件改为onmouseover 后就没有效果了

来源:8-2 编程练习

无畏青春

2020-09-21 14:44:06

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>canvas动画</title>
    <style>
    * {
        padding: 0;
        margin: 0;
    }

    canvas {
        background-color: lightblue;
    }
    </style>
</head>

<body>
    <canvas width="800px" height="800px" id="canvas">您的浏览器不支持canvas</canvas>
    <script>
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var posX = 100,
        posY = 0,
        dir = 1;
    var isMouseInRect = false; //判断鼠标是否在生成的方块里面
    canvas.onmousemove = function(e) {
        var mouseX = e.offsetX,
            mouseY = e.offsetY;
        if (mouseX > posX && mouseX < posX + 50 && mouseY > posY && mouseY < posY + 50) {
            isMouseInRect = true;
        } else {
            isMouseInRect = false;
        }
    }

    setInterval(function() {
        if (!isMouseInRect) { //表示当鼠标不在生成的矩形里面时 运行下面的代码
            posY += 10 * dir;
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.fillStyle = "green";
            context.fillRect(posX, posY, 50, 50);
            if (posY + 50 > canvas.height) {
                dir = -1;
            } else if (posY <= 0) {
                dir = 1;
            }
        }
    }, 100);
    </script>
</body>

</html>


写回答

1回答

好帮手慕慕子

2020-09-21

同学你好, 因为onmouseover事件在鼠标移入元素的时候触发一次, 之后在元素上移动时不会触发onmouseover事件的。 可以随便打印一个值测试一下,示例:

http://img.mukewang.com/climg/5f684e6e09992f1f09030354.jpg

打印结果就是只有每次移入移入画布的时候打印一次。 

onmousemove事件鼠标在元素上移动时会一直触发这个事件, 同学可以自己下去测试一下哦

如果我的回答帮助到了你, 欢迎采纳,祝学习愉快~~~

0

0 学习 · 6815 问题

查看课程