简体   繁体   中英

Jquery or Javascript Animating the Z-Index

I need the functionality of animating the z-index property of a specific HTML object. I've been able to achieve this animation in two ways that both have their difficulties/drawbacks. Successfully answering this question for me will fix one of the following two issues:

The first is by adapting the JQuery animate command with the step functionality outlined here by the accepted answer:

jQuery's $('#divOne').animate({zIndex: -1000}, 2000) does not work?

The problem with this method for me is that the $('#obj').stop(); command cannot prematurely end the animation when done in this way. It always finishes unless I destroy the object I'm working with and create a new one (which causes blinking obviously). If anyone knows of a way to properly stop a step animation like this, or a work-around for the issue, I'd love to see it.

var div = $('#obj');

$({z: ~~div.css('zIndex')}).animate({z: [-2000, 'linear']}, {
    step: function() {
        div.css('zIndex', ~~this.z);
    },
    duration: 10000
});

The second is using a setInterval loop on 20 MS (a speed that is sufficient for my needs) to simply adjust the z-index to what it should be at that point of the "animation". This works great for a few moments, then something causes it to stop working suddenly. The code still runs through the $('#obj').css('z-index', val); line, and val is changing, but it no longer updates the object in the DOM. I've tried it on slower timer settings as well with identical results. Anyone know why JQuery might suddenly no longer be able to set the Z-Index?

function () move {
    if (!(MoveX == 0 && MoveY == 0))
    {
        $('#obj').css('z-index', val);
    } 
}

$('#obj').stop() doesn't work for you because the animation isn't being performed on $('#obj') .

It is being performed on the object $({z: ...}) (with a custom step function). This means you should do something like

var anim = $({z: ~~div.css('zIndex')}).animate({z: [-2000, 'linear']}, {
  step: function() {
    div.css('zIndex', ~~this.z);
  },
  duration: 10000
});

// sometime later
anim.stop();

See this demo .


Edit For what it's worth, here is the same demo using an animation interval. I see a syntax error in your second snippet: the function declaration should be

function move() { ...

I assume that's a typo since your code wouldn't even parse. Other than that, I'm not sure why that solution didn't work for you.

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