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

我没有使用JQuery,但我知道他们有这样做的function。 我知道如何在JQuery中执行此操作,但我想要一个纯粹的js解决方案。

如何改变CSS不透明度设置? unix时间戳的精度为1000毫秒……因此可能是单向的。

使用clearTimeout和setTimeout将是另一种方式。

做这个的最好方式是什么。 我试着查看JQuery源代码,但无法弄清楚他们为fadeInfadeOut做了什么。

有关

如何在不透明度淡化中消除未使用的参数?

这是使用setTimeout的动画function。 你可以在这里看到它的工作: 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(); };