问题
I have a javaScript function.
JavaScript:
function opacZero(object){
var presentOpacity = (object.style.opacity);
object.style.opacity =presentOpacity-0.2;
setTimeout( function(){opacZero(object)}, 40);
}
Now when I pass som eobject to this function, its opacity should reduce till 0 and go beyond 0 (as I am not clearing the timeout anywhere). But this is not happening. The opacity reduces to 0.20000000000000007 and reduces no more. But when I subtract 0.3 (or more) instead of 0.2, it is giving the desired result. But why not with numbers less than 0.2. I have no idea why this is happening. Help PLease
回答1:
This is due to how Javascript handles floating point numbers. Check out this SO question for some suggestions on how to work around it.
EDIT
Here's a way to work around it:
function opacZero(object){
var presentOpacity = Math.floor(object.style.opacity * 10);
object.style.opacity = (presentOpacity - 2) / 10;
setTimeout( function(){opacZero(object)}, 40);
}
回答2:
This is a possible work around:
function opacZero(object){
curOpac = curOpac < 0.1 ? 0 : curOpac - 0.2;
object.style.opacity = curOpac;
setTimeout( function(){
opacZero(object)
}, 400);
console.log( curOpac );
}
var test = document.getElementById( 'test' ),
curOpac = 1;
test.style.opacity = 1;
opacZero( test );
http://jsfiddle.net/daCrosby/bhTNC/1/
回答3:
Seems a little more straightforward to just check for the troublesome small values and force those to 0. Also probably a good idea to stop the timer once you hit 0:
function opacZero(object){
var newOpacity = object.style.opacity - 0.2;
if (newOpacity < 0.2) {
newOpacity = 0;
}
object.style.opacity = newOpacity;
if (newOpacity !== 0) {
setTimeout(function(){opacZero(object)}, 40);
}
}
Working demo: http://jsfiddle.net/jfriend00/8qkFN/
Or, if you want something briefer:
function opacZero(object){
object.style.opacity = object.style.opacity < 0.4 ? 0 : object.style.opacity - 0.2;
if (object.style.opacity != 0) {
setTimeout(function(){opacZero(object)}, 40);
}
}
来源:https://stackoverflow.com/questions/15583723/javascript-opacity-should-reduce-to-0-and-then-become-negative