The following code is supposed to gently vary the color of a tab, which i pass into the function. However, the gradient only increases every new time that i enter the tab, instead of increasing the one time i put the mouse over...
<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>
For the timeout, element is undefined when using it as text. You should use an anoymous function:
var elem=element;//I find that this is needed in some browsers
setTimeout(function(){fadetext(elem);},50);
For what it's worth, you are missing a closing bracket }
at the end of fadetext
.
You're missing the curly brace to end the function:
<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>
Try replacing the setTimeout()
call with:
setTimeout(function(){fadetext(element);},50);
A more robust approach, with smooth animation. Usage: fadeText("elementid", 1000); Also, you can reuse this for any kind of animation. Just change the values between you interpolate, and the style setting part.
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 );
}
精彩评论