JavaScript:不透明度应降低为0,然后变为负数 [英] JavaScript: Opacity should reduce to 0 and then become negative

查看:83
本文介绍了JavaScript:不透明度应降低为0,然后变为负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javaScript函数.

I have a javaScript function.

JavaScript:

JavaScript:

function opacZero(object){
    var presentOpacity = (object.style.opacity);
    object.style.opacity =presentOpacity-0.2;
    setTimeout( function(){opacZero(object)}, 40);
}

现在,当我将soe eobject传递给此函数时,其不透明度应减少到0并超过0(因为我没有在任何地方清除超时).但是,这没有发生.不透明度降低到0.20000000000000007并且不再降低.但是,当我减去0.3(或更大)而不是0.2时,它给出了所需的结果.但是为什么不使用小于0.2的数字呢?我不知道为什么会这样.帮助请

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

推荐答案

这是由于Javascript处理浮点数的方式.查看此SO问题,以获取有关工作方式的一些建议

This is due to how Javascript handles floating point numbers. Check out this SO question for some suggestions on how to work around it.

编辑

这是解决它的一种方法:

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

这篇关于JavaScript:不透明度应降低为0,然后变为负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆