admin管理员组

文章数量:1310537

I am trying to add an opacity transition on a div. It should start at opacity 0 and once it is visible on the screen it should fade in slowly, to the maximum opacity.

Here is my code:

<div className="transition-opacity ease-in-out opacity-0 <STATE>:opacity-100 duration-300"> ... </div>

However, I do not know what state to use for my purpose. What should I replace the STATE from above with? Or is it not the right approach?

I am trying to add an opacity transition on a div. It should start at opacity 0 and once it is visible on the screen it should fade in slowly, to the maximum opacity.

Here is my code:

<div className="transition-opacity ease-in-out opacity-0 <STATE>:opacity-100 duration-300"> ... </div>

However, I do not know what state to use for my purpose. What should I replace the STATE from above with? Or is it not the right approach?

Share Improve this question asked Sep 21, 2022 at 14:26 Mister BabuMister Babu 1091 gold badge2 silver badges11 bronze badges 1
  • I would look at using IntersectionObserver to detect when it is in view, and then with some javascript, remove the opacity-0 class, and add opacity-100. – stickyuser Commented Sep 21, 2022 at 14:52
Add a ment  | 

3 Answers 3

Reset to default 5

You can define animation which will be envoked right after ponent will be rendered.

To define custom animation in tailwind:

  • go to tailwind.config.js
  • add new animation:
module.exports = {
   ...,
   theme: {
     ...,
     extend: {
       ...,
       keyframes: {
        appear: {
          "0%": {
            opacity: "0",
          },
          "100%": {
            opacity: "1",
          },
        },
       },
       animation: {
          appear: "appear 1s ease-in-out",
       }
     }
   }
  • in your file use your animation in tailwind way:
<div className="animate-appear" />

Think you are on the right track with this, you'd just need to toggle a class upon load:

const [loaded, setLoaded] = useState(false);

handleLoad = () => {
  setLoaded(true);
}

ponentDidMount() {
  window.addEventListener('load', this.handleLoad);
}

<div className={`${loaded ? "opacity-100" : "opacity-0"}`>

If there's a more elegant solution to this from a React expert, would be good to know :)

try adding this

<div className="duration-75">
...

本文标签: javascriptTailwind CSS transition on loadStack Overflow