Improper use of the += operator in JavaScript leads to increment errors
P粉178894235
2023-09-02 20:32:58
<p>I have a div that I'm trying to fade text into. </p>
<p>
<pre class="brush:js;toolbar:false;">function fadeIn(divNum) {
let id = null;
fadeDiv = document.getElementById("jsTest");
fadeDiv.innerHTML = "";
console.log(fadeDiv.style.opacity);
if (divNum == 1) {
fadeDiv.innerHTML = "Some text";
} else if (divNum == 2 ) {
fadeDiv.innerHTML = "Some different text";
} else if (divNum == 3) {
fadeDiv.innerHTML = "Still different text";
} else {
fadeDiv.innerHTML = "Oops! This shouldn't happen";
}
clearInterval(id);
id = setInterval(moveIt,100);
function moveIt() {
if (fadeDiv.style.opacity == 1) {
clearInterval(id);
} else {
fadeDiv.style.opacity = 0.1;
console.log(fadeDiv.style.opacity);
}
}
}</pre>
<pre class="brush:html;toolbar:false;"><div style="opacity: 0;" id="jsTest"></div>
<button class="boxButtonsb" onmouseover="fadeIn(1)">JavaScript Test</button></pre>
</p>
<p>When I hover, the opacity only decreases by <code>.1</code> and it looks like it's looping there forever. The console log shows endless <code>0.1</code> entries. </p>
<p> However, if I reverse it, so the initial opacity is 1, there is text starting in the div, and I set <code>fadeIn</code> actually by using <code>fadeDiv.style.opacity == 0</code> checked as if statement for <code>clearInterfal(id)</code> and decremented<code>fadeDiv.style.opacity< by <code>-= 0.1</code> ;/code> and it will work fine. </p>
<p>I have absolutely no idea why decrementing is correct but incrementing is not. </p>
CSS properties are always strings, not numbers. Your code executes
'0.1' 0.1
, and the result is'0.10.1'
, which is not a valid number, so may be truncated back to0.1
.One way to change it is to parse the result as a number.
HTMLELement::style
Contains string values and needs to be converted to floating point numbers: