Javascript: Fade element from specidied opacity to specified opacity?

冷暖自知 提交于 2019-11-29 17:54:01

There is no particular trick to it, you just set the opacity style to something other than 0 or 1 repeatedly in a timeout/interval.

Here's a stripped down fade function you can use as a starting point.

<script type="text/javascript">
    function fade(element, o0, o1, t) {
        // IE compatibility. Detect lack of native 'opacity' support, and ensure element
        // has layout for IE6-7.
        //
        var canopaque= 'opacity' in element.style;
        if (!canopaque && 'currentStyle' in element && element.currentStyle.hasLayout===false)
            element.style.zoom= '1';

        function setOpacity(o) {
            if (canopaque)
                element.style.opacity= ''+o;
            else
                element.style.filter= 'alpha(opacity='+Math.round(o*100)+')';
        }

        var t0= new Date().getTime();
        setOpacity(o0);
        var interval= setInterval(function() {
            var dt= (new Date().getTime()-t0)/t;
            if (dt>=1) {
                dt= 1;
                clearInterval(interval);
            }
            setOpacity(o1*dt+o0*(1-dt));
        }, 25);
    }
</script>
<p id="foo"> hello. </p>
<button onclick="fade(document.getElementById('foo'), 0.7, 0, 2000);">fade 0.7 to 0</button>

All the frameworks' effect libraries like JQuery or Prototype allow fading from and to arbitrary values.

  • In JQuery: FadeTo
  • In Prototype: Fade with the to: argument

Edit: Sorry, I overread that you don't want to use any frameworks. But they should at least give you an idea how to do it. Also, it should be easy to tweak any fading function to go from x to y instead of 0 to 1 - You'd just need to adjust the target values of 0 or 1 to something in between.

Use code from this example:

<html>
<head>
<title> </title>
    <script>
var nereidFadeObjects = new Object();
var nereidFadeTimers = new Object();
var opacitiz=0;  

//Функция предназначена для нумерации тегов
window.onload=function() {
  var e=document.getElementsByTagName('*')
  for (var i=0,l=e.length;i<l;i++) e[i].sourceIndex=i
}

//Вызов nereidFade() для разных браузеров при наведение и отводе курсора мышкой
            //@param object определяет из какого тега был вызов
//@param num -- 1  - навели курсов мышкой, 0 - отвели курсор мышки                        
function KrossBrows(object,num) {
        if (num==1) 
                if (!document.all) nereidFade(object, 1,30,0.1);
                else nereidFade(object, 100,30,10);
        else
                if (!document.all) nereidFade(object, 0.3,50,0.05);
                else nereidFade(object, 30,50,5);
}

//Отвечает за прозрачнность 
//@param object определяет из какого тега был вызов
//@param destOp конечная позиция для выполнения прозрачности
    //@param rate время которое потребуется на вызов функции
//@param delta шаг для прозрачности
function nereidFade(object, destOp, rate, delta){
        if (!document.all) opacitiz=object.style.opacity;
        else opacitiz=object.filters.alpha.opacity;

        clearTimeout(nereidFadeTimers[object.sourceIndex]);
        diff = destOp-opacitiz;
        direction = 1;
        if (opacitiz > destOp) direction = -1;

                delta=Math.min(direction*diff,delta);
        if (!document.all)                 object.style.opacity=parseFloat(object.style.opacity)+(direction*delta);
        else object.filters.alpha.opacity+=direction*delta;

    if (opacitiz != destOp){
            nereidFadeObjects[object.sourceIndex]=object;
                nereidFadeTimers[object.sourceIndex]=setTimeout("nereidFade(nereidFadeObjects["+object.sourceIndex+"],"+destOp+","+rate+","+delta+")",rate);
    }
}
</script>
</head>
<body>
<IMG onmouseover="KrossBrows(this,1)" style="FILTER: alpha(opacity=30);opacity:0.3"     onmouseout="KrossBrows(this,0)" height=31 alt="" src="ace.gif" width=88 vspace=2     border=0></A>
<IMG onmouseover="KrossBrows(this,1)" style="FILTER: alpha(opacity=30);opacity:0.3"     onmouseout="KrossBrows(this,0)" height=31 alt="" src="ace.gif" width=88 vspace=2     border=0></A>
</body>
            </html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!