简体   繁体   English

以简单的方式使用纯 Javascript 淡入和淡出

[英]Fade In and Fade Out using pure Javascript in a simple way

I've been trying to create a fadeIn & fadeOut animation using VanillaJS in my project but I literally don't understand what's the problem.我一直在尝试在我的项目中使用 VanillaJS 创建淡入淡出动画,但我真的不明白问题出在哪里。 I'm using SCSS.我正在使用 SCSS。 I made it simple for you.我为你做的很简单。

I tried visibility but it didn't work too.我尝试了visibility但它也不起作用。 like it appears eg for 200ms but then immediately disappears.就像它出现例如200ms ,然后立即消失。 In another way of explanation, it appears whenever I click on it (stable) and then goes away after 200ms (unstable).另一种解释是,每当我点击它时它就会出现(稳定),然后在200ms后消失(不稳定)。

 const fade = () => { const box = document.querySelector('#box'); box.classList.toggle('fade'); }; document.querySelector('#fadebtn').addEventListener('click', fade);
 #box { width: 70px; height: 50px; background: #FD7A6B; display: none; opacity: 0; -webkit-transition: 200ms ease-in-out; -moz-transition: 200ms ease-in-out; -o-transition: 200ms ease-in-out; transition: 200ms ease-in-out; } #box.fade { display: block !important; opacity: 1 !important; } // I also tried this, wondered it may work, but didn't. // .fade { // display: block !important; // opacity: 1 !important; // }
 <button type="button" id="fadebtn">Fade</button> <div id="box"></div>

I wrote this due to the title of the question: "Fade in ... pure javascript ... simple way."我写这个是因为问题的标题: “淡入......纯javascript......简单的方式。”

tl;dr https://jsfiddle.net/nqfud4j0/ tl;博士https://jsfiddle.net/nqfud4j0/

The following solution is a basic example of how you can use only Javascript to fade in/out to a desired value.以下解决方案是如何仅使用 Javascript 淡入/淡出到所需值的基本示例。 You could also use this with other values/properties, but it also serves as an example for basic tweening.您也可以将它与其他值/属性一起使用,但它也可以作为基本补间的示例。

It's intentionally using setInterval rather than requestAnimationFrame to demonstrate the example's use of time + controlled framerate rather than a delta or 'fast as possible.'它有意使用setInterval而不是requestAnimationFrame来演示示例使用时间 + 受控帧率而不是增量或“尽可能快”。 A good solution would abstract this logic into a tweening library that combines both RAF + intervals to manage latency between frames.一个好的解决方案是将此逻辑抽象为一个补间库,该库结合了 RAF + 间隔来管理帧之间的延迟。

function fadeTo(element, toValue = 0, duration = 200) {
    // Store our element's current opacity (or default to 1 if null)
    const fromValue = parseFloat(element.style.opacity) || 1;

    // Mark the start time (in ms). We use this to calculate a ratio
    // over time that applied to our supplied duration argument
    const startTime = Date.now();

    // Determines time (ms) between each frame. Sometimes you may not
    // want a full 60 fps for performance reasons or aesthetic 
    const framerate = 1000 / 60; // 60fps
    
    // Store reference to interval (number) so we can clear it later
    let interval = setInterval(() => {
        const currentTime = Date.now();

        // This creates a normalized number between now vs when we
        // started and how far into our desired duration it goes
        const timeDiff = (currentTime - startTime) / duration;

        // Interpolate our values using the ratio from above
        const value = fromValue - (fromValue - toValue) * timeDiff;
        
        // If our ratio is >= 1, then we're done.. so stop processing
        if (timeDiff >= 1) {
            clearInterval(interval);
            interval = 0;
        }
        
        // Apply visual. Style attributes are strings.
        element.style.opacity = value.toString();
    }, framerate)
}


// Element reference
const element = document.querySelector('div');

// Fade in and out on click
element.addEventListener('click', e => {
    // Animates our element from current opacity (1.0) to 0.25 for 1000ms
    fadeTo(element, 0.25, 1000);
    
    // Waits 1s, then animates our element's opacity to 1.0 for 500ms
    setTimeout(() => {
        fadeTo(element, 1.0, 500);
    }, 1000);
});

It all worked just in a simple way.这一切都以一种简单的方式运作。 remember that I use position: absolute;记住我使用position: absolute; , so it's your problem if you're not using absolute lol. ,所以如果你不使用absolute大声笑,那是你的问题。 have a good day.祝你有美好的一天。

 const fade = () => { const box = document.querySelector('.foo'); box.classList.toggle('fade'); }; document.querySelector('#bar').addEventListener('click', fade);
 .foo { position: absolute; top: 50px; left: 0; width: 100px; height: 75px; background-color: hsl(0, 0%, 86%); opacity: 0; transition: opacity 200ms ease-in-out; } .fade { opacity: 1 !important; }
 <button type="button" id="bar">Fade</button> <div class="foo"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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