Throttle - mouse follow effect example

Throttling strategy: As the name suggests, it can reduce the trigger frequency of events for a period of time.

It’s like launching a skill in a game. After Diao Chan’s first skill is used, if the skill is not cooled down well, there is no way to trigger the skill. Anti-shake is like returning to the city. It can be interrupted but you can return to the city for the last time. city. Throttling is performed the first time it is triggered, while anti-shake is performed the last time it is triggered.

 Full code:
 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./lib/jquery.js"></script>
    <style>
        html,
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        
        #ag {
            position: absolute;
        }
    </style>
</head>

<body>
    <img src="../angel.gif" alt="" id="ag">
    <script>
        // 获取小天使元素
        var angle = $('#ag');
        // 定义一个节流阀
        var timer = null;
        // 监听鼠标移动事件
        $(document).on('mousemove', function(e) {
            // 判断是否有节流阀
            if (timer) {
                return;
            }
            // 开启延时器
            timer = setTimeout(function() {
                angle.css('left', e.pageX + 'px').css('top', e.pageY + 'px');
                console.log(111);
                // 重置timer
                timer = null;
            }, 16)
        });
    </script>
</body>

</html>

Supongo que te gusta

Origin blog.csdn.net/qq_43781887/article/details/126921416
Recomendado
Clasificación