我正在尝试执行以下文件,但是,我永远无法让它工作。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Hello</title>
<style id="1">
@keyframes anim {
0% {
left: 0px;
top: 0px;
}
25% {
left: 200px;
top: 0px;
}
50% {
left: 200px;
top: 200px;
}
75% {
left: 0px;
top: 200px;
}
100% {
left: 0px;
top: 0px;
}
}
</style>
</head>
<body>
<h1 id="box"
style="animation-duration:6s;color:#FF0000;position:relative;animation-iteration-count: infinite;animation-name:anim"
onclick="A()">Hello</h1>
<button type="button" onclick="A()">click</button>
<script>
function A() {
var css = "@keyframes anim {0% {left:0px; top:0px;}25% {left:200px; top:" + Math.random() + "px;}50% {left:200px; top:200px;}75% {left:0px; top:200px;}100% {left:0px; top:0px;}}"
document.getElementById("1").innerHTML = css
}
</script>
</body>
</html>
答案 0 :(得分:1)
在css中设置变量如下:
<style>
:root {
--anim-top: 0px;
}
@keyframes anim {
0% {
left: 0px;
top: 0px;
}
25% {
left: 200px;
top: var(--anim-top);
}
50% {
left: 200px;
top: 200px;
}
75% {
left: 0px;
top: 200px;
}
100% {
left: 0px;
top: 0px;
}
}
</style>
并在javascript中更改该变量的值,如下所示:
<script>
document.body.style.setProperty('--anim-top',Math.random()+'px');
</script>