Fading an element onfocus and onblur
I have a single word counter on the page that counts the number of characters for each input element.
When an input element is focused, a fadeIn
function is triggered to fade in the counter element. When the input element loses focus i.e. is blurred, a fadeOut
function is triggered on the counter.
However when you focus and blur the elements several times and in fast intervals with either the mouse or the keyboard, the fade effect is noticed less and less. The counter which fades in and out ends up only blinking between opacity: 0 and 1. A page refresh is required to achieve the fade effect again, until it screws up again.
This problem is also triggered if you tab through all elements and regain your initial focus on the browser address bar.
Why does this happen? Could it have something to do with the fade function and setInterval
?
Here's an example fade function I use from http://www.scriptiny.com :
var fadeEffect=function(){
return{
init:function(id, flag, target){
this.elem = document.getElementById(id);
clearInterval(this.elem.si);
this.target = target ? target : flag ? 100 : 0;
this.flag = flag || -1;
this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
this.si = setInterval(function(){fadeEffect.tween()}, 20);
},
tween:function(){
if(this.alpha == this.target){
clearInterval(this.elem.si);
}else{
var value = Math.round(this.alpha + ((this开发者_如何学运维.target - this.alpha) * .05)) + (1 * this.flag);
this.elem.style.opacity = value / 100;
this.elem.style.filter = 'alpha(opacity=' + value + ')';
this.alpha = value
}
}
}
}();
Perhaps it's because you're not doing clearInterval()
properly. You are setting the interval like this:
this.si = setInterval();
but clearing the interval like this:
clearInterval(this.elem.si)
Shouldn't they both be this.si
or both be this.elem.si
?
Also, how are you invoking fadeEffect
? Are you using new fadeEffect()
? Are you sure that this
is being handled properly when you call methods?
Using jquery probably you are looking for such behaviour:
$(document).ready(function () {
$('#test').fadeTo('fast', 0.5); // to set default opacity. CSS can be used here
$('#test').focus(function () {
$(this).fadeTo('fast', 1);
}).blur(function () {
$(this).fadeTo('fast', 0.5);
});
});
here is live example: http://jsfiddle.net/hrzw7/1/
if you have a lot of such controls, use .class
selector: http://jsfiddle.net/hrzw7/3/
精彩评论