admin管理员组

文章数量:1417050

I want a div to follow the cursor-movement with a short delay like this: /

As you can see, the 'follower' has a short delay in the animation.

I've rebuild some function which is not working very well:

$(document).ready(function () {

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

    function handleMouseMove(event) {

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

        $(".cursor-follower").animate({
            left: (x - 16),
            top: (y - 16)
        }, 16);

        $(".cursor").css({
            left: (x - 4),
            top: (y - 4)
        });
    }
});

It's quite lagging and the animation is not very smooth and ease. Do you have another solution?

I want a div to follow the cursor-movement with a short delay like this: http://vanderlanth.io/

As you can see, the 'follower' has a short delay in the animation.

I've rebuild some function which is not working very well:

$(document).ready(function () {

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

    function handleMouseMove(event) {

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

        $(".cursor-follower").animate({
            left: (x - 16),
            top: (y - 16)
        }, 16);

        $(".cursor").css({
            left: (x - 4),
            top: (y - 4)
        });
    }
});

It's quite lagging and the animation is not very smooth and ease. Do you have another solution?

Share Improve this question asked Feb 12, 2018 at 21:49 JonasJonas 4775 silver badges23 bronze badges 2
  • Without looking at the site you posted, I'm guessing it's one of those continuous transitions with an easing function from the 2000s. – Derek 朕會功夫 Commented Feb 12, 2018 at 21:52
  • It is not a delay that is being used. It is just an easing function. – Korgrue Commented Feb 12, 2018 at 21:52
Add a ment  | 

1 Answer 1

Reset to default 5

You can achieve this effect with CSS transitions. In JavaScript you only have to update the position of the div.

$(document).on('mousemove', (event) => {
  $('.follower').css({
    left: event.clientX,
    top: event.clientY,
  });
});
.follower {
  width: 20px;
  height: 20px;
  background-color: grey;
  border-radius: 10px;
  transition-duration: 200ms;
  transition-timing-function: ease-out;
  position: fixed;
  transform: translate(-50%, -50%);
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="follower"></div>

本文标签: javascriptjQuery Follow cursor with delayStack Overflow