简体   繁体   中英

fadeIn fadeOut effect with Raw javascript

I am currently working on a experiment with RAW Javascript. I was wondering why it is not working. In fact I have scratched my head until there is no hair left... :P.

I am making a table with TR elements to be hovered over with some Javascript event. I think you will know exactly what I mean if you look at the code. The point is to get stuff to fade out first and then fade in afterwards when it reaches zero.

I am a beginner and maybe this can be done with the existing code. But of course if it is possible in another way of programming, I am open for suggestions.

THE CODE:

window.onload = changeColor;

var tableCells = document.getElementsByTagName("td");


function changeColor() {
    for(var i = 0; i < tableCells.length; i++) {
        var tableCell = tableCells[i];
        createMouseOutFunction(tableCell, i);
        createMouseOverFunction(tableCell, i);
    }
}


function createMouseOverFunction(tableCell, i) {
    tableCell.onmouseover = function() {
        tableCell.style.opacity = 1;
        createMouseOutFunction(tableCell, i);
    }
}

function createMouseOutFunction(tableCell, i) {
    var OpacitySpeed = .03;
    var intervalSpeed = 10;

    tableCell.onmouseout = function() {
        tableCell.style.opacity = 1;
        var fadeOut = setInterval(function() {
            if(tableCell.style.opacity > 0) {
                tableCell.style.opacity -= OpacitySpeed;
            } else if (tableCell.style.opacity <= 0) {
                clearInterval(fadeOut);
            }
        }, intervalSpeed);

        var fadeIn = setInterval(function(){
            if(tableCell.style.opacity <= 0){
                tableCell.style.opacity += OpacitySpeed;
            } else if(tableCell.style.opacity == 1){
                clearInterval(fadeIn);
            }
        }, intervalSpeed);

    }
}

Here is working example of your code ( with some corrections )

http://www.jsfiddle.net/gaby/yVKud/

corrections include

  • Start the fadein once the fadeout is completed ( right after you clear the fadeout )
  • ues the parseFloat() method, because the code failed when it reached negative values.
  • remove the createMouseOutFunction(tableCell, i); from the createMouseOverFunction because you assign it in the initial loop.

I think you'll probably need to use the this keyword in some of your event binding functions. However I haven't myself got your code to work.

I would recommend using a library such as jQuery . In particular .animate will probably be of use here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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