问题
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...
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>
EDIT: 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; }
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.
Here is a jsFiddle to show the result.
来源:https://stackoverflow.com/questions/19371647/js-setinterval-only-runs-once-when-animating-opacity