Home > Web Front-end > CSS Tutorial > How Can I Efficiently Disable and Re-enable CSS Transitions in JavaScript?

How Can I Efficiently Disable and Re-enable CSS Transitions in JavaScript?

Linda Hamilton
Release: 2024-11-28 22:47:11
Original
443 people have browsed it

How Can I Efficiently Disable and Re-enable CSS Transitions in JavaScript?

Disabling and Re-enabling CSS Transitions

In a typical web application, DOM elements can be subject to various CSS transitions. However, there may be instances where you need to temporarily disable these effects during certain operations, such as resizing an element.

Elegant Disablement and Re-enabling

To elegantly disable and re-enable CSS transitions, you can utilize a combination of CSS and JavaScript.

CSS Class:

Create a "notransition" CSS class to override the transition properties of an element:

.notransition {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  transition: none !important;
}
Copy after login

JavaScript:

Without jQuery:

const someElement = document.getElementById("some-element");

// Disable transitions
someElement.classList.add('notransition');

// Perform CSS changes
doWhateverCssChangesYouWant(someElement);

// Trigger a reflow
someElement.offsetHeight;

// Re-enable transitions
someElement.classList.remove('notransition');
Copy after login

With jQuery:

const $someElement = $('#some-element');

// Disable transitions
$someElement.addClass('notransition');

// Perform CSS changes
doWhateverCssChangesYouWant($someElement);

// Trigger a reflow
$someElement[0].offsetHeight;

// Re-enable transitions
$someElement.removeClass('notransition');
Copy after login

Explanation:

  1. Add the "notransition" class to disable transitions.
  2. Apply any desired CSS changes to the element.
  3. Trigger a forced reflow by reading the element's offsetHeight property.
  4. Remove the "notransition" class to re-enable transitions.

The above is the detailed content of How Can I Efficiently Disable and Re-enable CSS Transitions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template