如何创建不透明度渐变()?(对jQuery的改进)

How to create an opacity fade()? ( improvement over jQuery)

本文关键字:jQuery 不透明度 何创建 创建 渐变      更新时间:2023-09-26

我没有使用JQuery,但我知道他们有这样的功能。我知道如何在JQuery中做到这一点,但我想要一个纯js解决方案。

如何更改CSS不透明度设置的时间?unix时间戳的精度为1000毫秒。。。所以这可能是一种方式。

使用clearTimeout和setTimeout是另一种方法。

最好的方法是什么。我试着查看JQuery源代码,但无法弄清楚它们到底在为fadeInfadeOut做什么。

相关

如何消除不透明渐变中未使用的参数?

这里有一个使用setTimeout的动画函数。你可以在这里看到它的工作原理:http://jsfiddle.net/jfriend00/GcxdG/.

function toggleOpacity(id) {
    var el = document.getElementById(id);
    if (el.style.opacity == 1) {
        fadeObject(el, 1, 0, 2000)
    } else {
        fadeObject(el, 0, 1, 2000)
    }
}
function fadeObject(el, start, end, duration) {
    var range = end - start;
    var goingUp = end > start;
    var steps = duration / 20;   // arbitrarily picked 20ms for each step
    var increment = range / steps;
    var current = start;
    var more = true;
    function next() {
        current = current + increment;
        if (goingUp) {
            if (current > end) {
                current = end;
                more = false;
            }
        } else {
            if (current < end) {
                current = end;
                more = false;
            }
        }
        el.style.opacity = current;
        if (more) {
            setTimeout(next, 20);
        }
    }
    next();
}

注意:这还不适用于不响应opacity样式并且需要通过IE特定的filter设置来设置不透明度的旧IE版本。

for (var i = 1; i < 100; i += 1) { // change the += 1 for different smoothness
    (function(i) { 
        setTimeout(function() {
            el.style.opacity = (100 - i) * 0.01;
        }, i * 10);
    })(i);
}
/**
 **  SEffects - user can set the opacity fade to up or down and the specefied time
 */
var SEffects = function ( element ) {
    this.element = element;
};
SEffects.prototype.fade = function( direction, max_time ) {
    var element = this.element;
    element.elapsed = 0;
    clearTimeout( element.timeout_id );
    function next() {
        element.elapsed += 10;
        if ( direction === 'up' ) {
                element.style.opacity = element.elapsed / max_time;
            }
            else if ( direction === 'down' ) {
                element.style.opacity = ( max_time - element.elapsed ) / max_time;
            }
            if ( element.elapsed <= max_time ) {
                element.timeout_id = setTimeout( next, 10 );
            }
        }
        next();
    };