I want to make an image gradually emerge using opacity property, only to find that its opacity only increases 0.1 instead of 1. It seems that it only increases one time, but I set condition that it continue to increase until opacity reaches 1.
So I use another same image, whose opacity is 1. Then decrease opacity until opacity reaches 0. However, it finally disappears as expected.
It turns out that opacity can only change from 1 to 0, but can't change from 0 to 1?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<img src="https://cdn.pixabay.com/photo/2020/10/10/21/54/performers-5644247__480.jpg">
<img src="https://cdn.pixabay.com/photo/2020/10/10/21/54/performers-5644247__480.jpg">
<script>
let myView = document.querySelector('.view1');
myView.style.opacity = 1;
function changeOpacity() {
myView.style.opacity -= 0.01;
if (myView.style.opacity <= 0) {
clearInterval(timer);
}
}
let timer = setInterval(changeOpacity, 10);
let secondView = document.querySelector('.view2');
secondView.style.opacity = 0;
function changeAnotherOpacity() {
secondView.style.opacity = 0.1;
if (secondView.style.opacity >= 1) {
clearInterval(anotherTimer);
}
}
let anotherTimer = setInterval(changeAnotherOpacity, 10);
</script>
</body>
</html>
IDE might warn that opacity is a string, but it doesn't matter. The result is same even if write myView.style.opacity = "1"
CodePudding user response:
The Issue lies within the =
and -=
operators to Set the value. As -=
only applies for Mathematical operations, =
can also concatenate strings. In the first the String gets converted to a Number to use the -=
operator, therefore reducing the number value by 0.1 works as expected. But the =
operator will concatenate the value as a String, because the value of .style.opacity
is a String and therefore concatenating the 0.1 as a String resulting in "00.1", which is somewhat weird but will be corrected to "0.1". But the 2nd Iteration would resolve in "0.10.1" as the new value, which cant be corrected or even converted to a valid Number.
Hence you should adjust your code for compensating this behaviour:
function changeAnotherOpacity() {
secondView.style.opacity = Number(secondView.style.opacity) 0.1;
if (secondView.style.opacity >= 1) {
clearInterval(anotherTimer);
}
}