I want to click a button and animate an element with the web animation library, For some reason I cant target with document.getElementById
without getting an error.
The error is on document.getElementById
and is Object is possibly 'null'.ts(2531)
import React, {useContext} from "react";
const Home: React.FC = () => {
function startAnimation() {
var player = document.getElementById('home').animate([
{ transform: 'scale(1)', opacity: 1, offset: 0 },
{ transform: 'scale(.5)', opacity: .5, offset: .3 },
{ transform: 'scale(.667)', opacity: .667, offset: .7875 },
{ transform: 'scale(.6)', opacity: .6, offset: 1 }
], {
duration: 700,
easing: 'ease-in-out',
delay: 10,
iterations: Infinity,
direction: 'alternate',
fill: 'forwards',
});
}
return (
<nav onClick={startAnimation}>
Click Me
</nav>
<main id="home">
Animate me
</main>
);
}
export default Home;
TypeScript allows for type guards . If you check to see if the value is not null, then the error will not occur.
function startAnimation() {
var player = document.getElementById("home");
if (player !== null) {
// This side of the if-statement will never execute if player is null
player.animate(
[
{ transform: "scale(1)", opacity: 1, offset: 0 },
{ transform: "scale(.5)", opacity: 0.5, offset: 0.3 },
{ transform: "scale(.667)", opacity: 0.667, offset: 0.7875 },
{ transform: "scale(.6)", opacity: 0.6, offset: 1 }
],
{
duration: 700,
easing: "ease-in-out",
delay: 10,
iterations: Infinity,
direction: "alternate",
fill: "forwards"
}
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.