mouseOver上的Javascript递归不起作用?

时间:2010-06-29 14:24:12

标签: javascript

以下代码应该轻轻地改变选项卡的颜色,我将其传递给函数。但是,渐变只会在我进入选项卡的每个新时间增加,而不是增加一次我将鼠标放在...

<script type = "text/javascript">
        hex=255;
    function fadetext(element){ 

    if(hex>0) {
        hex-=11;
        element.style.backgroundColor="rgb("+hex+","+hex+","+hex+")";
        setTimeout("fadetext(element)",50); 
    }
    else
        hex=255;
    }
</script>


    <div id="tabs">
    <ul>
         <li><a href="tab-frame-css.html" class="selected" target="mainFrame"  onMouseOver = "fadetext(this)" onclick="loadit(this)">Personal details</a></li>
    </ul>
    </div>

5 个答案:

答案 0 :(得分:1)

对于超时,将元素用作文本时,元素未定义。你应该使用一个令人厌恶的功能:

var elem=element;//I find that this is needed in some browsers
setTimeout(function(){fadetext(elem);},50);

答案 1 :(得分:0)

对于它的价值,您在}结尾处缺少结束括号fadetext

答案 2 :(得分:0)

你错过了花括号来结束这个功能:

<script type = "text/javascript">
        hex=255;
    function fadetext(element){ 

    if(hex>0) {
        hex-=11;
        element.style.backgroundColor="rgb("+hex+","+hex+","+hex+")";
        setTimeout("fadetext(element)",50); 
    }
    else
        hex=255;
    }
} // You're missing this one here
</script>

答案 3 :(得分:0)

尝试将setTimeout()来电替换为:

setTimeout(function(){fadetext(element);},50); 

答案 4 :(得分:0)

更强大的强大方法,平滑动画。用法:fadeText(“elementid”,1000); 此外,您可以重复使用用于任何类型的动画。只需更改插值和样式设置部分之间的值。

function interpolate( start, end, pos ) {
  return start + ( pos * (end - start) );
}

function fadeText( dom, interval, delay ) {

      interval = interval || 1000;
      delay    = delay    || 10;

  var start    = Number(new Date());

  if ( typeof dom === "string" ) {
    dom = document.getElementById( dom );
  }

  function step() {

    var now     = Number(new Date()),
        elapsed = now - start,
        pos     = elapsed / interval,
        value   = ~~interpolate( 255, 0, pos );

    dom.style.backgroundColor =
    "rgb("+value+","+value+","+value+")";

    if ( elapsed < interval )
      setTimeout( step, delay );
  }

  setTimeout( step, delay );
}