设置不透明度动画时,JS setInterval()仅运行一次 [英] JS setInterval() only runs once when animating opacity

查看:109
本文介绍了设置不透明度动画时,JS setInterval()仅运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索并发现大多数有此问题的人都在传递函数调用而不是函数名称,即:setInterval(myFunc(),100)而不是setInterval(myFunc,100)

I've searched and seen that most people with this problem are passing a function call rather than function name ie: setInterval(myFunc(),100) instead of setInterval(myFunc,100)

但是我不是,它仍然无法正常工作...我也看到很多人说您需要对不透明性进行解析以使其正常工作,我已经尝试过了,但仍然可以同样的结果...

But I'm not, and it still won't work... I also saw a lot of people saying you need to parseFloat on the opacity to get it to work, I've tried that and it still yields the same result...

无论我是否包含if(i.style.opacity == 1)子句,功能runSubMenu1()似乎只运行一次

The function runSubMenu1() appears to run just one time regardless of whether i include the if(i.style.opacity==1) clause or not

不确定从这里要去哪里?建议?

Not sure where to go from here? advice?

<script type="text/javascript">

var run;
var runOpt;

function openSubMenu1(item) {
    runOpt=item;
    run = setInterval(runSubMenu1,100);

}

function runSubMenu1()  {
    var i=document.getElementById('menu-1-'+runOpt);

    if(i.style.opacity==1){clearInterval(run);}
    else{i.style.opacity+=.1;}


}


</script>

进行了jfriend00提及的更改,并且不透明度在与页面一起发送的原始CSS中设置为0,经过1次迭代后,不透明度似乎为.1

made changes mentioned by jfriend00, and opacity has a value of 0 set in original CSS sent with the page, after 1 iteration the opacity seems to be .1

推荐答案

您需要解析该值,因为它是一个字符串,否则+= .1会失败:

You need to parse the value, since it is a string, otherwise the += .1 fails:

    else { i.style.opacity = parseFloat(i.style.opacity) + .1; }

您要在".1"中添加.1,结果为:".1.1".将此值分配给不透明度会调用数字解析器,因为它是一个数字值,但由于它不是有效数字,因此会失败,因此回落到.1.该间隔无限循环,但是由于它从0移到.1,因此看起来只运行了一次.

You are adding .1 to ".1", which results in: ".1.1". Assigning this value to opacity invokes a number parser because it is a numeric value, but this fails, since it is not a valid number, so it falls back to .1. The interval loops infinitely, but since it only moves from 0 to .1, it looks like it only ran once.

这里是一个 jsFiddle 来显示结果.

Here is a jsFiddle to show the result.

这篇关于设置不透明度动画时,JS setInterval()仅运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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