试图让div“跟随”光标在mousemove上,但有延迟 [英] Attemping to get a div to "follow" cursor on mousemove, but with a delay

查看:394
本文介绍了试图让div“跟随”光标在mousemove上,但有延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建类似于旧鼠标轨迹的效果,其中div被延迟但跟随光标。

I want to create the effect similar to the old mouse trails where the div is delayed but follows the cursor.

我已经通过使用设置间隔来合理地接近触发动画到光标的坐标。

I have come reasonably close by using set interval to trigger an animation to the coordinates of the cursor.

$("body").mousemove(function (e) {
    if (enableHandler) {
        handleMouseMove(e);
        enableHandler = false;
    }
});

timer = window.setInterval(function(){
    enableHandler = true;
}, 250);

function handleMouseMove(e) {

  var x = e.pageX,
      y = e.pageY;

      $("#cube").animate({
        left: x,
        top: y
      }, 200);

}

JSFiddle

现在还有两个问题:


  1. '追逐'div是非常跳跃的(因为需要使用设定间隔)

  1. The 'chasing' div is very jumpy (because of the required use of set interval)

如果鼠标移动停止之前动画被触发,div保持原位,远离光标。

If the mouse move stops before the animation is triggered, the div is left in place, away from the cursor.


推荐答案

我做的略有不同。而不是使用 setInterval (甚至 setTimeout ) - 我只是让动画需要x毫秒才能完成。动画越长,下面的div似乎就越不敏感。

I did it slightly differently. Instead of using setInterval (or even setTimeout) - I just made the animation take x amount of milliseconds to complete. The longer the animation, the less responsive the following div will seem to be.

我注意到的唯一问题是,如果鼠标移动很多,它会被备份。

The only problem I notice is that it gets backed up if the mouse is moved a lot.

$(document).ready(function () {

    $("body").mousemove(function (e) {
        handleMouseMove(e);
    });

    function handleMouseMove(event) {

        var x = event.pageX;
        var y = event.pageY;

        $("#cube").animate({
            left: x,
            top: y
        }, 1);
    }
});

https://jsfiddle.net/jvmravoz/1/

这篇关于试图让div“跟随”光标在mousemove上,但有延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆