简体   繁体   中英

Transition animation using inline styles (CSS or jQuery)

I'm using the progress bar that comes with the Ninja Forms Multi-Part Form addon and here's the setup of the progress bar.

<div class="nf-progress-container">
    <div class="nf-progress" style="width: 0%;"></div>
</div>

When I advance to each subsequent part of the multi-part form, some JS or jQuery changes the width of the inline style attribute in the .nf-progress div and the progress bar fills in with each step completed.

To help you visualize, here's what my UI looks like with styling.

这是我的样式进度条的样子,以帮助您可视化它

I'd like for the progress bar to animate the .nf-progress div as each step is completed. I thought it was going to be as simple as transition: width 1s ease; , but it's not working (even with -webkit-transition ). Here's what I tried.

.nf-progress-container .nf-progress {
    transition: width 1s ease;
    -webkit-transition: width 1s ease;
}

I did a little more investigating and found that you can't animate inline styles with the transition css property. Not sure why, but you can't do it, apparently.

I kept digging and found an article that gets me closer here with pure css animation keyframes.

@-webkit-keyframes progress-bar {
   0% { width: 0; }
}
@-moz-keyframes progress-bar {
   0% { width: 0; }
}
@keyframes progress-bar {
   0% { width: 0; }
}

.nf-progress-container .nf-progress { 
  -webkit-animation: progress-bar 1s;
  -moz-animation: progress-bar 1s;
  animation: progress-bar 1s;
}

The benefit here is that I actually get some kind of animation. The problem with this approach though is that the animation starts at width:0% for every step of the progress bar. I want the element to transition from the previous width, whatever it was, to the new inline style width.

Does anyone know how to do this with CSS or if there is a way to accomplish this with jQuery?

Where did you read it's impossible to transition the width of an element with inline styles? This is possible:

 function increaseWidth() { var elem = document.querySelector('span'); elem.style.width = elem.clientWidth + 50 + 'px'; } setInterval(increaseWidth, 600) 
 span { height: 20px; width: 50px; transition: width 0.5s; background: purple; display: inline-block; } 
 <span/> 

In your case, a third party JavaScript library you are using is deleting then recreating the bar element you want to animate. This will prevent your animations from running.

If you really need the bar to animate, you can modify the source code of the third party app to ensure it mutates but does not destroy and recreate the bar element. Or you can write your own animating bar, which is quite straightforward (see above).

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