js——曲线运动

版权声明:转发博客 请注明出处 否则必究 https://blog.csdn.net/lucky541788/article/details/82315392
 window.onload = function () {
            var enjoy = document.getElementById('enjoy');

            enjoy.onclick = function () {
                inchingMove(400, 300, .1, function () {
                    inchingMove(100, 100, .1);
                });
            };

            /**
             * 缓动位移动画
             * @param x 位移x目标
             * @param y 位移y目标
             * @param num 缓动系数
             * @param fn 回调函数
             */
            function inchingMove(x, y, num, fn) {
                var timer = null;
                var targetX = parseInt(window.getComputedStyle(enjoy)['left']),
                    targetY = parseInt(window.getComputedStyle(enjoy)['top']);
                console.log(targetX, targetY);

                timer = setInterval(function () {
                    targetX += x >= targetX ? Math.ceil((x - targetX) * num) : Math.floor((x - targetX) * num);
                    targetY += y >= targetY ? Math.ceil((y - targetY) * num) : Math.floor((y - targetY) * num * 4);//使x,y的缓动系数不一致则曲线运动
                    enjoy.style.left = targetX + 'px';
                    enjoy.style.top = targetY + 'px';
                    console.log(targetX, targetY);
                    if (targetX === x && targetY === y) {
                        if (fn) {
                            fn();
                        }
                        clearInterval(timer);
                    }
                }, 50);
            }
        }

猜你喜欢

转载自blog.csdn.net/lucky541788/article/details/82315392
今日推荐