用raw javascript淡化fadeOut效果

时间:2010-12-15 11:33:59

标签: javascript

我目前正在使用RAW Javascript进行实验。我想知道它为什么不起作用。事实上,我已经摸不着头,直到没有留下头发......:P。

我正在创建一个包含TR元素的表,以便在一些Javascript事件中悬停。我想如果你看一下代码,你会知道我的意思。关键是让东西先淡出然后在达到零时淡入淡出。

我是初学者,也许可以使用现有代码完成。但当然,如果有可能采用另一种编程方式,我愿意接受建议。

代码:

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);

    }
}

2 个答案:

答案 0 :(得分:2)

以下是您的代码的示例(带有一些更正

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

更正包括

  • 淡出完成后启动淡入淡出(清除淡出后
  • 使用parseFloat()方法,因为代码在达到负值时失败。
  • createMouseOutFunction(tableCell, i);移除createMouseOverFunction,因为您在初始循环中分配了它。

答案 1 :(得分:0)

我认为您可能需要在某些事件绑定函数中使用this关键字。但是我没有让你的代码工作。

我建议使用jQuery之类的库。特别是.animate可能会在这里使用。

相关问题