简体   繁体   中英

JQuery Animate : Change the destination of a prop during the animation

I made a image scrolling with the mouse.

The image scroll to a position based on the mouse position percentage of the window height.

$(imageContainer).mouseenter(function(e){
    var scrollingTo = ((e.pageY/$(this).height())-.083) * ( $(imageContainer).prop('scrollHeight') - $(imageContainer).height() );
    hijacked = true;
    $(imageContainer).animate({scrollTop:scrollingTo},300,function(){hijacked=false;});
}).mousemove(function(e){
    if(hijacked) return;
    var scrollingTo = ((e.pageY/$(this).height())-.083) * ( $(imageContainer).prop('scrollHeight') - $(imageContainer).height() );
    $(imageContainer).scrollTop(scrollingTo);
}); 

So. in that line

$(imageContainer).animate({scrollTop:scrollingTo},300,function(){hijacked=false;});

I want that scrollingTo change. Because during the animation, the user can move the mouse, changing the scrollingTo variable.

Alright, I managed to cook together a hacky way of dynamically altering an animation. My understanding of the internal animation queue for jQuery is not great, but as far as I know there's no way to alter a queued animation, other than to make it stop. Anyway, here's the key code for an example that alters position, which should be adaptable to scrolling (in fiddle form ):

$(document).ready(function () {
    var last_update = 0;
    $(document).on("mousemove", function (e) {
        if (Date.now() - last_update > 50) {
            $mover = $("#mover");
            $mover.stop(); 
            $mover.animate({ left: e.pageX, top: e.pageY}, 200, "linear");            
            last_update = Date.now();
        }
    });                    
});

There were a couple of tricks to make it work, I'll go through them and try to explain how I believe they could be adapted to scrolling:

  • The main idea is that on mousemove, the prior event is cancelled, and a new one is started. I don't believe this will require any changes for scrolling.

  • Some forms of animation accelerate/decelerate over the course of the animation - it's too hard to preserve this in a constantly changing animation (at least without writing a custom animation function), so the animation easing is set to "linear".

  • rapidly changing animations takes time (especially for an event as common as mousemove), so there's a limit on how often the animation can change. Before a change to the animation is made, it's ensured that no changes have been made in the last .05 seconds (this is done with "last_update").

I believe if you just swap out the animation properties for your own (scrollTop), this should do what you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM