使用JavaScript触发CSS动画不起作用

时间:2019-11-26 19:51:53

标签: javascript html css css-animations

我想使用JavaScript触发CSS动画。问题是我想在3秒后启动动画,但是动画开始没有延迟!

为什么?我在开始时通过添加暂停的类来暂停动画...但是它不起作用..!?

//pause the animation at first
document.getElementById("tutorialText").classList.add("paused");

//after 3 seconds initiate the animation
setTimeout(function(){
  document.getElementById("tutorialText").classList.add("played");
}, 3000)
@font-face {
  font-family: "Open Sans";
  src: url(fonts/OpenSans-Bold.ttf) format("truetype");
  font-weight: bold;
}


html{
	overflow:hidden;
}

 
.mainTexts{
	position: absolute;
    font-family: 'Open Sans', sans-serif;
    font-weight: bold;
    font-size: 7.5vw;
    color: rgb(242, 242, 242);
    left: 18.5vw;
    top: -45vh;
    animation: roll 1s linear infinite;
}



@-webkit-keyframes roll {
  0% {
    top: -50vh;
  }
  100% {
    top: 12.369791666666666vh;
  }
}

.paused {
   -webkit-animation-play-state: paused !important; 
}

.played {
   -webkit-animation-play-state: running !important; 
}
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="style.css"> 
</head>

<body>
<div class="mainTexts">
 <p id="tutorialText">Tutorial</p>
</div>
  <script src="script.js"></script>
</body>

</html>

我缺少什么?

1 个答案:

答案 0 :(得分:3)

因为animation属性设置为mainTexts类,而不是tutorialText元素。只需定位具有animation属性的元素即可。

此外,删除-webkit-东西。不再需要。

//pause the animation at first
document.getElementById("tutorialText").classList.add("paused");

//after 3 seconds initiate the animation
setTimeout(function(){
  document.getElementById("tutorialText").classList.add("played");
}, 3000)
@font-face {
  font-family: "Open Sans";
  src: url(fonts/OpenSans-Bold.ttf) format("truetype");
  font-weight: bold;
}


html{
	overflow:hidden;
}

 
.mainTexts{
	position: absolute;
    font-family: 'Open Sans', sans-serif;
    font-weight: bold;
    font-size: 7.5vw;
    color: rgb(242, 242, 242);
    left: 18.5vw;
    top: -45vh;
    animation: roll 1s linear infinite;
}



@keyframes roll {
  0% {
    top: -50vh;
  }
  100% {
    top: 12.369791666666666vh;
  }
}

.paused {
   animation-play-state: paused !important; 
}

.played {
   animation-play-state: running !important; 
}
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="style.css"> 
</head>

<body>
<div id="tutorialText" class="mainTexts">
 <p>Tutorial</p>
</div>
  <script src="script.js"></script>
</body>

</html>